用requests库和BeautifulSoup4库爬取新闻列表

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.选一个自己感兴趣的主题,做类似的操作,为“爬取网络数据并进行文本分析”做准备。

posted @ 2017-09-28 21:56  sister姐姐  阅读(201)  评论(0编辑  收藏  举报