0
点赞
收藏
分享

微信扫一扫

使用BeautifulSoup爬取新浪所有国内要闻

双井暮色 2022-03-15 阅读 22

最近要做一个食品安全方面的项目,需要爬取新闻。于是想到之前用BeautifulSoup爬虫还是非常方便的,今天正好试了一下,可行。

爬取的链接如下:​​http://news.sohu.com/1/0903/61/subject212846158.shtml​​

结构如下:


使用BeautifulSoup爬取新浪所有国内要闻_开发者工具


从第二页开始的链接格式是:​​​​​​

逐页递减(即1091、1090如此)。

需要的内容: 标题、时间、来源、作者、全文。

准备: urllib2, BeautifulSoup, lxml


先引入这几个库

import ​urllib2
import ​lxml
from ​bs4 ​import ​BeautifulSoup


先用开发者工具得到headers(当然我们这里不用headers也可以)

headers = {
   ​"User-Agent"​: ​"ozilla/5.0 (Macintosh; Intel Mac OS X 10_12_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36"​}


def sina_news(url,i):
request = urllib2.Request(url,headers=headers)
#发送请求,带headers
response = urllib2.urlopen(request)
#得到response
html_doc = response.read()
#读取得到HTML文件
soup = BeautifulSoup(html_doc,'lxml')
#对HTML使用lxml解析器进行解析
titles = soup.select('td.newsblue1 > a:nth-of-type('+str(i)+')')
#利用selector获得titles
time = soup.select('td.newsblue1 > span:nth-of-type('+str(i)+')')
#同上
print titles[0].get_text()
#由于select返回的是表,表的第一个元素是我们要的,所以titles[0],.get_text()是为了去掉一些HTML代码,只得到内容值
print time[0].get_text()
print titles[0]['href']


利用selector进行解析的时候是用到了开发者工具的定位功能,定位元素后,右键​copy-selector即可,​当然要注意nth-child(x)需要改成nth-of-type(x),在这里我们用了

nth-of-type('​+​str​(i)+​')'​)

这样的表达方式,是因为在该页面的结构中,新闻是以子项目排列的。如第一条就是nth-of-type(1),第二条就是nth-of-type(2),如此列推。测试一下结果:



for i in range(1,201):
sina_news('http://news.sohu.com/1/0903/61/subject212846158.shtml',i)



结果如下:


使用BeautifulSoup爬取新浪所有国内要闻_html_02


现在仅仅是解决了标题、时间、链接,我们还有来源,作者。但是我们已经获得了每一条新闻的链接,那么这就很好办了。


我们先看一下每一条新闻的结构:



使用BeautifulSoup爬取新浪所有国内要闻_xml_03

使用BeautifulSoup爬取新浪所有国内要闻_html_04


同理、很容易就能提取出来源、责任编辑。代码如下:

def get_source​(url):
   request = urllib2.Request(url​,headers​=headers)
   response = urllib2.urlopen(request)
   html_doc = response.read()
   soup = BeautifulSoup(html_doc​,'lxml'​)
   sources = soup.select(​'#media_span'​)
   editor = soup.select(​'#editor_baidu'​)
   ​return ​sources​,​editor


在原来的函数中增加如下代码:

sources,editor = get_source(titles[0]['href'])
if(sources):
print sources[0].get_text()
if(editor):
print editor[0].get_text()



由于来源和责任编辑不一定每一条新闻都有,因此这里加了一个判断条件。现在看看效果。


使用BeautifulSoup爬取新浪所有国内要闻_xml_05


效果还可以,再提取所有页面的内容

def get_singalpage_all​(url):
   ​for ​i ​in range​(​1,201​):
       sina_news(url​,​i)

def get_all_page​():
   url = ​'http://news.sohu.com/1/0903/61/subject212846158'
   
for ​i ​in range ​(​1091,990,​-​1​):
       wholeURL = url + ​'_' ​+ ​str​(i) + ​'.shtml'
       
​get_singalpage_all(wholeURL)


调用一下:

get_singalpage_all(​'http://news.sohu.com/1/0903/61/subject212846158.shtml'​)
get_all_page()


成功爬取了所有国内要闻。

上面已经是全部源代码了,当然如果你觉得这样看很麻烦的话,可以在这里下载:

​​

​​

​​
举报

相关推荐

0 条评论