长沙分类信息网-长沙新闻网

python爬虫之爬取腾讯新闻

2021-6-21 21:49:52发布7次查看
 
所以要爬取要闻下的所有新闻标题和链接就需要一个一个分页的爬取。下面开始写代码。
首先获取腾讯新闻页面内容,写一个获取页面的接口。
先导入本次抓取所必备的库
[python] view plain copy
<span style=font-size:18px;># -*- coding:utf-8 -*-    #python抓取网页必备的库  import urllib   import urllib2  #正则表达式  import re  #随机数生成  import random  #gzip  import gzip  from stringio import stringio</span>  构建请求头部,请求页面
[python] view plain copy
<span style=font-size:18px;>#构建页面请求的头部  headers = {'user-agent':user_agent, referer:referer}  #构建页面请求  request = urllib2.request(url, headers=headers)  #请求目的页面,设置超时时间为45秒  response =  urllib2.urlopen(request, timeout = 45)</span>   请求腾讯新闻页面,返回的页面数据有时会经过gzip压缩,如果直接读取会出现二进制码,所以在处理返回的页面时需要做gizp解压的处理[python] view plain copy
<span style=font-size:18px;>#如果经过gzip压缩则先解压,否则直接读取  if response.info().get('content-encoding') == 'gzip':      buf = stringio(response.read())      f = gzip.gzipfile(fileobj=buf)      html = f.read()  else:      html = response.read()</span>   整理代码段,最后封装成页面请求接口
[python] view plain copy
<span style=font-size:18px;>#user-agent  user_agent = mozilla/5.0 (windows nt 6.1; win64; x64) applewebkit/537.36 (khtml, like gecko) chrome/58.0.3029.110 safari/537.36    #抓取页面接口,参数为地/址和referer  def gethtml(url, referer = none):      try:          #构建页面请求的头部          headers = {'user-agent':user_agent, referer:referer}          #构建页面请求          request = urllib2.request(url, headers=headers)          #请求目的页面,设置超时时间为45秒          response =  urllib2.urlopen(request, timeout = 45)            html = none          #如果经过gzip压缩则先解压,否则直接读取          if response.info().get('content-encoding') == 'gzip':              buf = stringio(response.read())              f = gzip.gzipfile(fileobj=buf)              html = f.read()          else:              html = response.read()            return html      #如果请求异常      except urllib2.urlerror, e:          if hasattr(e, code):              print e.code          elif hasattr(e, reason):              print e.reason          return none      #其他异常      except exception,e:          return none</span>  页面请求接口写好后,接下来分析如何要闻页签下的所有数据,要闻页签下有几个分页,当我们在请求分页时可以看出腾讯要闻分页的请求时通过ajax实现的,打开google浏览器的network,可以看到请求分页时的信息。如图:
分析请求地/址会发现,每一次的分页请求都是一个地/址后面加上一个随机数,而地/址中会有本次请求的索引。
这样我们就可以构建分页的请求地/址,获取每个分页的信息。但是在这之前我们不清楚腾讯要闻中会有多少个分页。
分析腾讯新闻的页面,我们最后会发现首页中的一段js标出了腾讯要闻中有多少分页。
因此我们首先抓取腾讯新闻页面内容,获取到要闻有多少分页,在构建分页请求,最后取出页面信息中所有的新闻
标题和原文链接就好了。代码如下:
[python] view plain copy
<span style=font-size:18px;>def tencentstart():      #腾讯新闻地/址      index_url = 'http://news.qq.com/top_index.shtml#hotnews'      #腾讯要闻请求地/址      sub_url = http://news.qq.com/c/2013ywlist_{0}.htm      #页面数获取正则      page_patterns = 'getstring.pagecount.*?=.*?(\d+);'      #标题和链接获取正则      news_patterns = '<em.*?<a.*?href=(.*?).*?>(.*?)</a>.*?</em>'      #头部信息相关      tencent_refer = http://news.qq.com/      #获取腾讯新闻页面      html = gethtml(index_url)      #取得要闻页面总数      pattern = re.compile(page_patterns, re.s)      countre = re.search(pattern, html)      if html == none:          print(未获取到页面)          return none      count = 1      if countre != none:          count = int(countre.group(1))      #构建分页地/址,请求分页数据      for index in range(count):          realindex = index + 1          #构建地/址          url = sub_url.format(realindex)+'?'+str(random.random())          html = gethtml(url, tencent_refer)          if html == none:              continue          #编译标题和链接获取正则          pattern = re.compile(news_patterns, re.s)          #获取所有标题和链接          res = re.findall(pattern, html)          if res == none:              continue          #打印所有标题和链接          for item in res:              print(item[0]+\n)              print(item[1]+\n)      if __name__ == '__main__':      tencentstart()</span>  最后运行脚本,可以看到打印出的腾讯要闻页签中的所有标题和链接

西安飞凡网络技术咨询有限公司
400 011 2010

该用户其它信息

推荐信息

长沙分类信息网-长沙新闻网
关于本站