爬蟲是請求⽹網站並提取數據的⾃自動化程序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
崔老師的課程對我有很大的幫助,再次感謝。服務器