獲取一篇新聞的所有信息

給定一篇新聞的連接newsUrl,獲取該新聞的所有信息php

標題、做者、發佈單位、審覈、來源html

發佈時間:轉換成datetime類型正則表達式

點擊:api

  • newsUrl
  • newsId(使用正則表達式re)
  • clickUrl(str.format(newsId))
  • requests.get(clickUrl)
  • newClick(用字符串處理,或正則表達式)
  • int()

整個過程包裝成一個簡單清晰的函數。ide

嘗試去爬取一個你感興趣的網頁。函數

 

 1 import re
 2 import requests
 3 from bs4 import BeautifulSoup
 4 from datetime import datetime
 5 
 6 #獲取新聞的全部信息
 7 def news(url):
 8     res = requests.get(url)
 9     res.encoding = 'utf-8'
10     soup = BeautifulSoup(res.text,'html.parser')
11     newsTitle = soup.select('.show-title')[0].text #標題
12     author = soup.select('.show-info')[0].text.split()[2] #做者
13     auditor = soup.select('.show-info')[0].text.split()[3] #審覈
14     source = soup.select('.show-info')[0].text.split()[4] #來源
15     showinfo = soup.select('.show-info')[0].text
16     newsday = newsdt(showinfo) #時間
17     newsclick = click(url) #點擊次數
18     news = print(newsTitle,newsday,author,auditor,source,newsclick)
19     return news
20 
21 #獲取點擊量
22 def click(url):
23     clickurl='http://oa.gzcc.cn/api.php?op=count&id=10789&modelid=80'
24     res=requests.get(clickurl)
25     click=res.text.split('.html')[-1].lstrip("('").rstrip("');")
26     return click
27 
28 #獲取發佈時間
29 def newsdt(url):
30     soup = BeautifulSoup(res.text,'html.parser')
31     showinfo = soup.select('.show-info')[0].text
32     newsdate=showinfo.split()[0].split(':')[1]
33     newstime=showinfo.split()[1]
34     newsday=newsdate+' '+newstime
35     dt=datetime.strptime(newsday,'%Y-%m-%d  %H:%M:%S')
36     return dt
37 
38 
39 
40 url='http://news.gzcc.cn/html/2018/xiaoyuanxinwen_1227/10789.html'
41 news(url)
運行代碼

運行結果截圖url

相關文章
相關標籤/搜索