1. 用requests库和BeautifulSoup库,爬取校园新闻首页新闻的标题、链接、正文。
import requestsfrom bs4 import BeautifulSoupfor news in soup.select('li'): if len(news.select('.news-list-title')) > 0: t = news.select('.news-list-title')[0].text dt = news.select('.news-list-info')[0].contents[0].text a = news.select('a')[0].attrs['href'] c = news.select('.news-list-description')[0].contents[0] print(dt,t,a,c)
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'] #链接 resd = requests.get(a) resd.encoding = 'utf-8' soupd = BeautifulSoup(resd.text, 'html.parser') print(soupd.select('.show-info')[0].text) #正文 info =soupd.select('.show-info')[0].text dt =info.lstrip('发布时间:')[:19] #发布时间 i =info.find('来源') if i>0: s = info[info.find('来源:')].split()[0].lstrip('来源:') #来源: break
3. 将其中的发布时间由str转换成datetime类型。
from datetime import datetime str = '2018-03-30 17:10:12 ' dt=datetime.strptime('str,%Y-%a-%d %H:%M:%S') now = datetime.now() type(now) now.strptime('%Y-%a-%d %H:%M:%S')