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')
1. 用requests库和BeautifulSoup库,爬取校园新闻首页新闻的标题、链接、正文。
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'] #链接res1=requests.get(a)res1.encoding='utf-8'soup1=BeautifulSoup(res1.text,'html.parser')d=soup1.select('#content')[0].text #正文print(t,a,d)
2. 分析字符串,获取每篇新闻的发布时间,作者,来源,摄影等信息。
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'] #链接res1=requests.get(a)res1.encoding='utf-8'soup1=BeautifulSoup(res1.text,'html.parser')info=soup1.select('.show-info')[0].textprint(info)
3. 将其中的发布时间由str转换成datetime类型。
from datetime import datetime
str = '2018-04-02 17:10:12 '
datetime.strptime(str,'%Y-%m-%d %H:%M:%S ')
print('\n',str)