1. 用requests庫和beautifulsoup庫,爬取校園新聞首頁新聞的標題、鏈結、正文。
import requestsfrom 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:
t = news.select('.news-list-title')[0].text # 標題
a = news.select('a')[0].attrs['href'] # 鏈結
resd = requests.get(a)
resd.encoding = 'utf-8'
soupd = beautifulsoup(resd.text,'html.parser') # 開啟詢問詳情頁
c = soupd.select('#content')[0].text # 正文
2. 分析字串,獲取每篇新聞的發布時間,作者,**,攝影等資訊。
3. 將其中的發布時間由str轉換成datetime型別。
4. 將完整的**及執行結果截圖發布在作業上。
import requestsfrom bs4 import beautifulsoup
res = requests.get('')
res.encoding = 'utf-8'
soup = beautifulsoup(res.text,'html.parser')
# print(soup)
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'] # 鏈結
resd = requests.get(a)
resd.encoding = 'utf-8'
soupd = beautifulsoup(resd.text,'html.parser') # 開啟詢問詳情頁
print(soupd.select('#content')[0].text)
print(d,t,a)
break
for news in soup.select('li'):
if len(news.select('.news-list-title')) > 0:
t = news.select('.news-list-title')[0].text # 標題
d = news.select('.news-list-description')[0].text
a = news.a.attrs['href']
resd = requests.get(a)
resd.encoding = 'utf-8'
soupd = beautifulsoup(resd.text,'html.parser')
# c = soupd.select('#content')[0].text # 正文
info = soupd.select('.show-info')[0].text
# print(info)
# print(a)
# print(d)
# print(c)
# print(t)
# break
from datetime import datetime
dati = datetime.strptime(dt, '%y-%m-%d %h:%m:%s')
print(dati, dati.strftime('%y/%m/%d'))
# print(dt,zz,ly)
if (info.find("攝影:") > 0):
sy = info[info.find("攝影:"):].split()[0].lstrip('攝影:') # 攝影
爬取校園新聞首頁的新聞
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 ...