爬取校園新聞首頁的新聞的詳情,使用正則表達式,函數抽離
阿新 • • 發佈:2018-04-07
嘗試 htm des script its etc 新聞 ttr sid
1. 用requests庫和BeautifulSoup庫,爬取校園新聞首頁新聞的標題、鏈接、正文、show-info。
2. 分析info字符串,獲取每篇新聞的發布時間,作者,來源,攝影等信息。
3. 將字符串格式的發布時間轉換成datetime類型
4. 使用正則表達式取得新聞編號
5. 生成點擊次數的Request URL
6. 獲取點擊次數
7. 將456步驟定義成一個函數 def getClickCount(newsUrl):
8. 將獲取新聞詳情的代碼定義成一個函數 def getNewDetail(newsUrl):
9. 嘗試用使用正則表達式分析show info字符串,點擊次數字符串。
import requests from bs4 import BeautifulSoup from datetime import datetime import locale import re locale.setlocale(locale.LC_CTYPE,‘chinese‘) newsurl = ‘http://news.gzcc.cn/html/xiaoyuanxinwen/‘ res = requests.get(newsurl) #返回response res.encoding = ‘utf-8‘ soup = BeautifulSoup(res.text,‘html.parser‘) def getClickCount(newsUrl): #獲取點擊次數 newsId = re.findall(‘\_(.*).html‘, newsUrl)[0].split(‘/‘)[1] #使用正則表達式取得新聞編號 clickUrl = ‘http://oa.gzcc.cn/api.php?op=count&id={}&modelid=80‘.format(newsId) clickStr = requests.get(clickUrl).text return(re.search("hits‘\).html\(‘(.*)‘\);",clickStr).group(1))def getNewDetail(newsUrl): #獲取新聞詳情 resd = requests.get(newsUrl) # 返回response resd.encoding = ‘utf-8‘ soupd = BeautifulSoup(resd.text, ‘html.parser‘) print(‘標題:‘ + title) print(‘描述:‘ + description) print(‘鏈接:‘ + newsUrl) info = soupd.select(‘.show-info‘)[0].text time = re.search(‘發布時間:(.*) \xa0\xa0 \xa0\xa0作者:‘, info).group(1) dtime = datetime.strptime(time, ‘%Y-%m-%d %H:%M:%S‘) #將字符串格式的發布時間轉換成datetime類型 print(‘發布時間:{}‘.format(dtime)) print(‘作者:‘ + re.search(‘作者:(.*)審核:‘, info).group(1)) print(‘審核:‘ + re.search(‘審核:(.*)來源:‘, info).group(1)) print(‘來源:‘ + re.search(‘來源:(.*)攝影:‘, info).group(1)) print(‘攝影:‘ + re.search(‘攝影:(.*)點擊‘, info).group(1)) print(‘點擊次數:‘ + getClickCount(a)) print(‘正文:‘+soupd.select(‘.show-content‘)[0].text) for news in soup.select(‘li‘): if len(news.select(‘.news-list-title‘))>0: title = news.select(‘.news-list-title‘)[0].text description = news.select(‘.news-list-description‘)[0].text a = news.a.attrs[‘href‘] getNewDetail(a) break
結果截圖:
爬取校園新聞首頁的新聞的詳情,使用正則表達式,函數抽離