改做業要求來源於:https://edu.cnblogs.com/campus/gzcc/GZCC-16SE2/homework/2894php
給定一篇新聞的連接newsUrl,獲取該新聞的所有信息html
標題、做者、發佈單位、審覈、來源python
發佈時間:轉換成datetime類型正則表達式
點擊:api
整個過程包裝成一個簡單清晰的函數。函數
具體代碼以下:url
import requests from bs4 import BeautifulSoup from datetime import datetime url='http://news.gzcc.cn/html/2019/xiaoyuanxinwen_0320/11029.html' def new(url): res = requests.get(url) res.encoding = ('utf-8') soup = BeautifulSoup(res.text, 'html.parser') title = soup.select('.show-title')[0].text.split() author = soup.select('.show-info')[0].text.split()[2] auditor = soup.select('.show-info')[0].text.split()[3] come = soup.select('.show-info')[0].text.split()[4] # 獲取點擊次數 clickurl = 'http://oa.gzcc.cn/api.php?op=count&id=11029&modelid=80' res2 = requests.get(clickurl) click = res2.text.split('.html')[-1].lstrip("('").rstrip("');") # 獲取時間 newsdate = soup.select('.show-info')[0].text.split()[0].split(':')[1] newstime = soup.select('.show-info')[0].text.split()[1] time = newsdate + ' ' + newstime time = datetime.strptime(time, '%Y-%m-%d %H:%M:%S') p = print(title, '\n', author, '\n', auditor, '\n', come, '\n', time, '\n', "點擊:", click) return p new(url)
效果以下圖:orm