• 8.Python爬虫实战一之爬取糗事百科段子


    大家好,前面入门已经说了那么多基础知识了,下面我们做几个实战项目来挑战一下吧。那么这次为大家带来,Python爬取糗事百科的小段子的例子。

    首先,糗事百科大家都听说过吧?糗友们发的搞笑的段子一抓一大把,这次我们尝试一下用爬虫把他们抓取下来。

    1.抓取糗事百科热门段子

    2.过滤带有图片的段子

     1 #coding:utf-8
     2 import urllib
     3 import urllib2
     4 import re
     5 page = 1
     6 url = 'https://www.qiushibaike.com/hot/page/1/'+str(page)
     7 user_agent = 'Mozilla/4.0 (compatible;MSIE 5.5;Windows NT)'
     8 headers = {'User-Agent':user_agent}
     9 
    10 try:
    11     request = urllib2.Request(url,headers=headers)
    12     response = urllib2.urlopen(request)
    13     qiubaiPattern =re.compile('<div.*?author.*?alt="(.*?)>.*?content.*?span>(.*?)</.*?number">(.*?)<',re.S)
    14     infos = re.findall(qiubaiPattern,response.read().decode('utf-8'))
    15     for info in infos:
    16         for a in info:
    17             str = a.replace('<br/>','
    ') #将段子正文中的<br/>替换成回车
    18             print str.strip() #删除字符中的首尾空格
    19 
    20 except urllib2.URLError,e:
    21         if hasattr(e,'code'):
    22             print e.code
    23         if hasattr(e,'reason'):
    24             print e.reason

    在这里不打算详细讲解这个代码,以后有空了再回来补上 嘻嘻

  • 相关阅读:
    HDU 1813 Escape from Tetris
    BZOJ 2276 Temperature
    BZOJ 4499 线性函数
    BZOJ 3131 淘金
    HDU 5738 Eureka
    POJ 2409 Let it Bead
    POJ 1286 Necklace of Beads
    POJ 1696 Space Ant
    Fox And Jumping
    Recover the String
  • 原文地址:https://www.cnblogs.com/stephenmc/p/7487168.html
Copyright © 2020-2023  润新知