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

习题1:选一个自己感兴趣的主题,做类似的操作,为“爬取网络数据并进行文本分析”做准备。

复制代码
import requests
from bs4 import BeautifulSoup
url='http://www.96192.com/'
res=requests.get(url)
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
        time=news.select('.news-list-info')[0].contents[0].text
        url1=news.select('a')[0]['href']
        bumen=news.select('.news-list-info')[0].contents[1].text
        description=news.select('.news-list-description')[0].text 
        print(time,title,bumen,url)
复制代码

 

习题2:用requests库和BeautifulSoup4库,爬取校园新闻列表的时间、标题、链接、来源

复制代码
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')
for news in soup.select('li'):
    if len(news.select('.news-list-title'))>0:
        title=news.select('.news-list-title')[0].text 
        time=news.select('.news-list-info')[0].contents[0].text#时间
        url1=news.select('a')[0]['href']#url
        bumen=news.select('.news-list-info')[0].contents[1].text
        description=news.select('.news-list-description')[0].text 
        print(time,title,bumen,url)
复制代码

posted on 2017-10-18 08:55  25-李泽易  阅读(199)  评论(0编辑  收藏  举报

导航