在本篇博客中,我们将使用selenium爬取新浪新闻中滚动页面的所有新闻内容,包括题目、时间、来源、正文,并存入MongoDB数据库。网址:https://news.sina.com.cn/roll。
打开后,发现这里都是一些滚动新闻,每隔1分钟就会刷新:
我们右键查看网页源代码,发现并没有当前页面的信息:
在源码页面搜索当前第一条新闻,并没有找到。
右键检查:
发现有当前页面的信息。说明当前页面是动态页面,即通过javascript渲染后得到的。因此,通过requests请求,是无法得到页面信息的,它得到的是网页最原始的代码,和右键查看网页源代码得到的是一致的。所以,我们需要使用selenium,模拟浏览器运行,来处理动态页面,从而爬取新闻信息。
程序主体框架如下:
import pymongo
import requests
from requests import RequestException
from selenium import webdriver
from bs4 import BeautifulSoup
from selenium.common.exceptions import NoSuchElementException
def get_response(url):
pass
def get_news(link):
# 获取新闻的详细信息
pass
def get_page_news():
#获取当前页面所有新闻的url
pass
if __name__ == '__main__':
#连接mongodb
client = pymongo.MongoClient('mongodb://localhost:27017')
#指定数据库
db = client.News
#指定集合
news_col = db.sinaRollNews
#打开浏览器
browser = webdriver.Chrome()
browser.implicitly_wait(10)
#打开网址
browser.get('https://news.sina.com.cn/roll/')
#获取当前页面新闻的url
get_page_news()
while True:
try:
#找到下一页按钮 并点击
'''
<a href="javascript:void(0)" onclick="newsList.page.next();return false;">下一页</a>
'''
browser.find_element_by_xpath('//a[@onclick