1. 用requests库和BeautifulSoup库,爬取校园新闻首页新闻的标题、链接、正文。
import requests
from bs4 import BeautifulSoup
from datetime import datetime
newsurl = ‘http://news.gzcc.cn/html/xiaoyuanxinwen/‘
res = requests.get(newsurl)
res.encoding = ‘utf-8‘
soup = BeautifulSoup(res.text,‘html.parser‘)
a=soup.select(‘li‘)
for news in a:
if len(news.select(‘.news-list-title‘))>0:
# 获取标题
b=news.select(‘.news-list-title‘)[0].contents[0]
# 获取链接接
c = news.select(‘a‘)[0].attrs[‘href‘]
# 获取正文
res1 = requests.get(c)
res1.encoding = ‘utf-8‘
soup1 = BeautifulSoup(res1.text, ‘html.parser‘)
d=soup1.select(‘#content‘)[0].text
2. 分析字符串,获取每篇新闻的发布时间,作者,来源,摄影等信息。
#发布时间
info = soup1.select(".show-info")[0].text;
e = info.lstrip(‘发布时间:‘)[:19]
#作者
f=info[info.find(‘作者:‘):info.find(‘审核:‘)].lstrip(‘作者:‘).split()[0]
#来源
g = info[info.find(‘来源:‘):info.find(‘点击:‘)].lstrip(‘来源:‘).split()[0]
#摄影
h = info[info.find(‘摄影:‘):].split()[0].lstrip(‘摄影:‘)
3. 将其中的发布时间由str转换成datetime类型。
# 获取当前的时间
now_time = datetime.now();
now_time.year
# 将字符串转化为时间
print(datetime.strptime(e, "%Y-%m-%d %H:%M:%S"))
# 将时间转化为字符串
print(now_time.strftime(‘%Y\%m\%d‘))
4. 将完整的代码及运行结果截图发布在作业上。
import requests
from bs4 import BeautifulSoup
from datetime import datetime
newsurl = ‘http://news.gzcc.cn/html/xiaoyuanxinwen/‘
res = requests.get(newsurl)
res.encoding = ‘utf-8‘
soup = BeautifulSoup(res.text,‘html.parser‘)
a=soup.select(‘li‘)
for news in a:
if len(news.select(‘.news-list-title‘))>0:
# 获取标题
b=news.select(‘.news-list-title‘)[0].contents[0]
# 获取链接接
c = news.select(‘a‘)[0].attrs[‘href‘]
# 获取正文
res1 = requests.get(c)
res1.encoding = ‘utf-8‘
soup1 = BeautifulSoup(res1.text, ‘html.parser‘)
d=soup1.select(‘#content‘)[0].text
# print(b+" "+c+" "+d)
#发布时间
info = soup1.select(".show-info")[0].text;
e = info.lstrip(‘发布时间:‘)[:19]
#作者
f=info[info.find(‘作者:‘):info.find(‘审核:‘)].lstrip(‘作者:‘).split()[0]
#来源
g = info[info.find(‘来源:‘):info.find(‘点击:‘)].lstrip(‘来源:‘).split()[0]
#摄影
h = info[info.find(‘摄影:‘):].split()[0].lstrip(‘摄影:‘)
# 获取当前的时间
now_time = datetime.now();
now_time.year
# 将字符串转化为时间
# print(datetime.strptime(e, "%Y-%m-%d %H:%M:%S"))
# 将时间转化为字符串
print(b+" "+c+" "+e+" "+f+" "+g+" "+" "+h+" "+now_time.strftime(‘%Y\%m\%d‘));
