1. 用requests庫和beautifulsoup庫,爬取校園新聞首頁新聞的標題、鏈結、正文。
import requests執行結果圖:from bs4 import beautifulsoup
res = requests.get('')
res.encoding = 'utf-8'
soup = beautifulsoup(res.text,'html.parser')
for news in soup.select('li'):
if len(news.select('.news-list-title'))>0:
d = news.select('.news-list-info')[0].contents[0].text #時間
t = news.select('.news-list-title')[0].text #標題
a = news.select('a')[0].attrs['href'] #url
print(d, t, a)
2. 分析字串,獲取每篇新聞的發布時間,作者,**,攝影等資訊。
res2 = requests.get(a)執行結果圖:res2.encoding = 'utf-8'
soup2 = beautifulsoup(res2.text,'html.parser')
x = soup2.select('.show-content')[0].text
info = soup2.select('.show-info')[0].text.split()
# print(soup2.select('#content')[0].text)
print(s,zz,sh,ly)
3. 將其中的發布時間由str轉換成datetime型別。
from datetime import datetime執行結果圖:time = '2018-04-01 11:57:00'
a = datetime.strptime(time, '%y-%m-%d %h:%m:%s')
print(type(a))
print(a, a.strftime('%y/%m/%d'))
4. 將完整的**及執行結果截圖發布在作業上
import requests執行結果圖from bs4 import beautifulsoup
from datetime import datetime
res = requests.get('')
res.encoding = 'utf-8'
soup = beautifulsoup(res.text,'html.parser')
for news in soup.select('li'):
if len(news.select('.news-list-title'))>0:
d = news.select('.news-list-info')[0].contents[0].text #時間
t = news.select('.news-list-title')[0].text #標題
a = news.select('a')[0].attrs['href'] #url
print(d,t,a)
res2 = requests.get(a)
res2.encoding = 'utf-8'
soup2 = beautifulsoup(res2.text,'html.parser')
x = soup2.select('.show-content')[0].text
info = soup2.select('.show-info')[0].text.split()
# print(soup2.select('#content')[0].text)
cc = datetime.strptime(s, '%y-%m-%d %h:%m:%s')
print(cc,type(cc))
print(cc.strftime('%y/%m/%d'),zz,sh,ly)
爬取校園新聞首頁的新聞
1.用requests庫和beautifulsoup庫,爬取校園新聞首頁新聞的標題 鏈結 正文 show info。2.分析info字串,獲取每篇新聞的發布時間,作者,攝影等資訊。import requests newsurl res requests.get newsurl 返回response物...
爬取校園新聞首頁的新聞
1.用requests庫和beautifulsoup庫,爬取校園新聞首頁新聞的標題 鏈結 正文 show info。import requests from bs4 import beautifulsoup newsurl res requests.get newsurl res.encoding ...
爬取校園新聞首頁的新聞
1.用requests庫和beautifulsoup庫,爬取校園新聞首頁新聞的標題 鏈結 正文 show info。2.分析info字串,獲取每篇新聞的發布時間,作者,攝影等資訊。import requests from bs4 import beautifulsoup from datetime ...