1. 用requests庫和BeautifulSoup庫,爬取校園新聞首頁新聞的標題、連接、正文。html
import requests from bs4 import BeautifulSoup url = 'http://news.gzcc.cn/html/xiaoyuanxinwen/' res = requests.get(url) res.encoding = 'utf-8' soup = BeautifulSoup(res.text, 'html.parser') news = soup.select('li') for new in news: if len(new.select('.news-list-title')) > 0: title = new.select('.news-list-title')[0].text href = new.select('a')[0].attrs['href'] text = new.select('.news-list-description')[0].text print(title) print(href) print(text+'\n')
圖片只展現部分url
2. 分析字符串,獲取每篇新聞的發佈時間,做者,來源,攝影等信息。spa
import requests from bs4 import BeautifulSoup url = 'http://news.gzcc.cn/html/xiaoyuanxinwen/' res = requests.get(url) res.encoding = 'utf-8' soup = BeautifulSoup(res.text, 'html.parser') news = soup.select('li') for new in news: if len(new.select('.news-list-title')) > 0: title = new.select('.news-list-title')[0].text href = new.select('a')[0].attrs['href'] text = new.select('.news-list-description')[0].text res = requests.get(href) res.encoding = 'utf-8' soup = BeautifulSoup(res.text, 'html.parser') info = soup.select('.show-info')[0].text content = info.split() time = content[0].lstrip('發佈時間:') + " " + content[1] author = content[2].lstrip('做者:') check = content[3].lstrip('審覈:') source = content[4].lstrip("來源:") print(time, author, check, source)
3. 將其中的發佈時間由str轉換成datetime類型。code
from datetime import datetime time = '2018-04-04 05:20:34' a = datetime.strptime(time, '%Y-%m-%d %H:%M:%S') print(type(a)) print(a, a.strftime('%Y/%m/%d'))
4. 將完整的代碼及運行結果截圖發佈在做業上。htm