标签:技术 parser encoding http toolbar 标题 port 自己 ext
1.用requests库和BeautifulSoup4库,爬取校园新闻列表的时间、标题、链接、来源。
import requests from bs4 import BeautifulSoup network = ‘http://news.gzcc.cn/html/jxky/‘ res = requests.get(network) res.encoding=‘utf-8‘ soup = BeautifulSoup(res.text,‘html.parser‘) for news in soup.select(‘li‘): if len(news.select(‘.news-list-title‘))>0: title = news.select(‘.news-list-title‘)[0].text url = news.select(‘a‘)[0][‘href‘] time = news.select(‘.news-list-info‘)[0].contents[0].text main = news.select(‘.news-list-description‘)[0].text source = news.select(‘.news-list-info‘)[0].contents[1].text print(‘链接:{}‘.format(url)) print(‘标题:{}‘.format(title)) print(‘正文:{}‘.format(main)) print(‘时间:{}‘.format(time)) print(‘来源:{}‘.format(source))
3.将其中的时间str转换成datetime类型。
import requests from bs4 import BeautifulSoup from datetime import datetime network = ‘http://news.gzcc.cn/html/jxky/‘ res = requests.get(network) res.encoding=‘utf-8‘ soup = BeautifulSoup(res.text,‘html.parser‘) for news in soup.select(‘li‘): if len(news.select(‘.news-list-title‘))>0: title = news.select(‘.news-list-title‘)[0].text url = news.select(‘a‘)[0][‘href‘] time = news.select(‘.news-list-info‘)[0].contents[0].text timed = datetime.strptime(time,‘%Y-%m-%d‘) main = news.select(‘.news-list-description‘)[0].text source = news.select(‘.news-list-info‘)[0].contents[1].text print(‘链接:{}‘.format(url)) print(‘标题:{}‘.format(title)) print(‘正文:{}‘.format(main)) print(‘时间:{}‘.format(timed)) print(‘来源:{}‘.format(source))
4.选一个自己感兴趣的主题,做类似的操作,为“爬取网络数据并进行文本分析”做准备。
用requests库和BeautifulSoup4库爬取新闻列表
标签:技术 parser encoding http toolbar 标题 port 自己 ext
原文地址:http://www.cnblogs.com/sisters/p/7608831.html