爬取校园新闻首页的新闻
1. 用requests库和BeautifulSoup库,爬取校园新闻首页新闻的标题、链接、正文。
import requests
from bs4 import BeautifulSoup
from datetime import datetime
res = requests.get("http://news.gzcc.cn/html/xiaoyuanxinwen/")
res.encoding = 'utf-8'
soup = BeautifulSoup(res.text, 'html.parser')
for news in soup.select('li'):
if len(news.select('.news-list-title')) > 0:
r = news.select('.news-list-title')[0].text #正文内容
d = news.select('.news-list-info')[0].contents[0].text #新闻发布时间
t = news.select('.news-list-info')[0].contents[1].text #来源
g = news.select('a')[0].attrs['href'] #链接
print(r,d,t,g)
2. 分析字符串,获取每篇新闻的发布时间,作者,来源,摄影等信息。
resd = requests.get(g)
resd.encoding = 'utf-8'
soupd = BeautifulSoup(resd.text, 'html.parser')
x = soupd.select('.show-content')[0].text
t1 = soupd.select('.show-info')[0].text.split() #每篇新闻的发布时间,作者,来源
print(t1)
s = t1[0].lstrip('发布时间:') + " " + t1[1] #发布时间
s1 = t1[2].lstrip('作者:') #作者
s2 = t1[3].lstrip('审核:') #审核
s3 = t1[4].lstrip("来源:") #来源
print(s, s1, s2, s3)
3. 将其中的发布时间由str转换成datetime类型。
now_time = datetime.now()
now_time.year
exchangetime = datetime.strptime(publish_time,"%Y-%m-%d %H:%M:%S") #字符转换为时间
exchangestring = now_time.strftime('%Y\%m\%d') #时间转换为字符
print(exchangetime)<br>print(exchangestring)
4. 将完整的代码及运行结果截图发布在作业上。
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')
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'] #连接
print(d, t, a)
# 通过连接获取新闻网页
res2 = requests.get(a)
res2.encoding = 'utf-8'
soup2 = BeautifulSoup(res2.text, 'html.parser')
# 取得新闻正文
z=soup2.select('#content')[0].text
print(z)
#取得发布时间、作者等数据项
info=soup2.select('.show-info')[0].text
print(info)
dt = info.lstrip('发布时间:')[:19]
at = info[info.find('作者:'):info.find('审核:')].split()[0].lstrip('作者:')
sh = info[info.find('审核:'):].split()[0].lstrip('审核:')
ly = info[info.find('来源:'):].split()[0].lstrip('来源:')
print(dt,at,sh,ly)
from datetime import datetime
dati = datetime.strptime(dt, '%Y-%m-%d %H:%M:%S')
# print(type(dati))
print(dati, dati.strftime('%Y/%m/%d'))
break

浙公网安备 33010602011771号