爬虫是请求⽹网站并提取数据的⾃自动化程序html
通过讨论,分析,对比各个新闻门户网站的排行榜,最终选取了内容正规、不良信息少、广告少的网易新闻排行榜。每一个整点爬取一次,选取点击率最高的前20条热门新闻。即红框所选内容。
python
目标网页:http://news.163.com/special/0001386F/rank_news.html
经过分析网页源代码得知,这个网页排行榜并非经过JavaScript动态加载生成。因此网页爬取后能够直接处理,简单利用BeautifulSoup + requests库便可实现。mysql
# 导入相应的包
from bs4 import BeautifulSoup
import requests
import re
import datetime
from connect_mysql import *
# 获取当前时间并指定格式为2018041018
time = datetime.datetime.now().strftime("%Y%m%d%H")
url = r'http://news.163.com/special/0001386F/rank_news.html'
# 模拟真实浏览器进行访问
headers = {'User-Agent':
'Mozilla/5.0 (Windows NT 10.0; WOW64) '
'AppleWebKit/537.36 (KHTML, like Gecko) '
'Chrome/55.0.2883.87 Safari/537.36'}
response = requests.get(url, headers=headers)
page_html = response.text
soup = BeautifulSoup(page_html, 'html.parser')
首先经过分析网站结构得知,咱们须要的数据在class = tabContents active的div下的全部a标签中,而这个div又嵌套在class = area-half left的div中。因此咱们写以下代码,从网页源代码中找到全部符合要求的标题,限制20条。web
titles = soup.find('div', 'area-half left').find('div', 'tabContents active').find_all('a', limit=20)
仅需一行代码,咱们就已经获取到了咱们须要的部分数据。接下来继续获取新的对咱们有用的数据,并存放到数据库。正则表达式
因为网页标题显示不全,因此上一步爬取的标题,部分不完整。因此咱们须要进一步爬取,步骤和上述几个操做相似,爬取新闻连接,新闻内容,新闻完整标题。这三个内容,并调用本身写的方法,将数据存放到数据库。并用re库对内容进行简单处理(去除\n\t\r ),具体实现以下。sql
for title in titles:
''' news_url:新闻连接 news_html:新闻页网页源代码 '''
news_url = (str(title.get('href')))
news_response = requests.get(news_url, headers=headers)
news_html = news_response.text
# 将获取到的内容转换成BeautifulSoup格式,并将html.parser做为解析器
news_soup = BeautifulSoup(news_html, 'html.parser')
# 从网页源代码中找到属于post_text类的div,并将全部p标签内容存入列表news_contents
if news_soup.find('div', 'post_text') is None: # 若是网页丢失,跳出本次循环
continue
news_title = news_soup.find('h1')
contents = news_soup.find('div', 'post_text').find_all('p')
news_contents = []
for content in contents:
if content.string is not None:
#去掉特殊字符
news_contents.append(re.sub('[\r\n\t ]', '', str(content.string)))
#字符串拼接
news_contents = ''.join(news_contents)
# 将爬取到的数据存入数据库
insert_wangyinews_into_mysql(wangyi_news, str(news_title.string), news_url, news_contents, time)
这样,一个简单的爬虫就完成了,不要小看这几十行代码,它们在本项目中发挥了巨大的做用。数据库
本文所用开发环境:
anaconda 5.1
pycharm浏览器
本文第一部分是崔庆才老师的python3网络爬虫视频教程的笔记:
课程连接:https://cuiqingcai.com/4320.html
崔老师的课程对我有很大的帮助,再次感谢。服务器