爬取校园新闻首页的新闻
1. 用requests库和BeautifulSoup库,爬取校园新闻首页新闻的标题、链接、正文。
1 # -*- coding: UTF-8 -*- 2 import requests 3 from bs4 import BeautifulSoup 4 5 url = 'http://news.gzcc.cn/html/xiaoyuanxinwen/' 6 res = requests.get(url) 7 res.encoding = 'utf-8' 8 9 soup = BeautifulSoup(res.text,'html.parser') 10 #print(soup) 11 12 for news in soup.select('li'): 13 if len(news.select('.news-list-title')) > 0 : 14 d= news.select('.news-list-info')[0].contents[0].text 15 t= news.select('.news-list-title')[0].text 16 a = news.select('a')[0].attrs['href'] 17 print("date = "+d,"text = "+t,"href = "+a)
2. 分析字符串,获取每篇新闻的发布时间,作者,来源,摄影等信息。
1 resd = requests.get(a) 2 resd.encoding = 'utf-8' 3 soupd = BeautifulSoup(resd.text,'html.parser') 4 c = soupd.select('#content')[0].text 5 info = soupd.select(".show-info") 6 print(info[0].text)
3. 将其中的发布时间由str转换成datetime类型。
1 info_text = '发布时间:2018-04-01 11:57:00 作者:陈流芳??审核:权麟春 来源:马克思主义学院 点击:次' 2 dt = info_text.lstrip('发布时间:')[:19] 3 sh = info_text[info_text.find('审核:'):].split()[0].lstrip('审核:') 4 print(type(dt),dt) 5 from datetime import datetime 6 date_format = datetime.strptime(dt,'%Y-%m-%d %H:%M:%S') 7 print(type(date_format),date_format)