找回密码
 立即注册

扫一扫,访问微社区

QQ登录

只需一步,快速开始

查看: 4858|回复: 2

[代码与实例] python2.7.6 和正则表达式 抓取糗事百科,带评论

1

主题

1

帖子

1

积分

贫民

积分
1
pythonLearner 发表于 2015-12-13 19:18:10 | 显示全部楼层 |阅读模式
本帖最后由 pythonLearner 于 2015-12-13 19:31 编辑
  1. __author__ = 'KS'
  2. # -*- coding: utf-8 -*-

  3. import urllib2
  4. import re


  5. def getContentOrComment(urlJoin):
  6.     user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'
  7.     headers = {'User-Agent': user_agent}
  8.     req = urllib2.Request(url=urlJoin, headers=headers)
  9.     response = urllib2.urlopen(req)
  10.     content = response.read()
  11.     return content


  12. # 文章地址
  13. url = "http://www.qiushibaike.com/textnew/page/%d"
  14. # 评论地址
  15. commentUrl = "http://www.qiushibaike.com/article/%s"
  16. page = 0
  17. while True:
  18.     getFromCustomer = raw_input("next page ? print Enter key to continue or 'exit' to stop\n")
  19.     if getFromCustomer == "exit":
  20.         break
  21.     page += 1
  22.     urlJoin = url % page
  23.     print urlJoin
  24.     articlePage = getContentOrComment(urlJoin)
  25.     # print content
  26.     # 把评论一起抠出来,文章郑泽匹配
  27.     # group[0]是文章id
  28.     # group[1]是文章内容
  29.     # group[2]是注释
  30.     rexArticle = r'<div[\s]+class\="article[\s]+block[\s]+untagged[\s]+mb15"[\s]+id\=\'qiushi_tag_(\d+?)\'\>[' \
  31.                  r'\s\S]*?\<div[' \
  32.                  r'\s]+class\="content"\>[\s]*([\S]+?)[\s]*(\<!--\d*--\>)*[\s]*\</div\>'
  33.     rexComment = r'\<span[\s]+class\="body"\>([^\n{][\s\S]+?)\</span\>'
  34.     patternArticle = re.compile(rexArticle)
  35.     patternComment = re.compile(rexComment)

  36.     for string in re.findall(patternArticle, articlePage):
  37.         articleId = string[0]
  38.         articleContent = string[1]
  39.         commentTimes = 1
  40.         print '\n'
  41.         print articleContent
  42.         commentPage = getContentOrComment(commentUrl % articleId)
  43.         for comment in re.findall(patternComment, commentPage):
  44.             print "   ", commentTimes, "楼回复:", comment
  45.             commentTimes += 1
  46.         print '\n'
复制代码

回复

使用道具 举报

0

主题

1

帖子

14

积分

贫民

积分
14
sin_alpha 发表于 2016-3-27 14:12:45 | 显示全部楼层
谢谢楼主分享,学到不少知识。

请教一下 如果只需要读articleid   
rexArticle =r'<div[\s]+class="article[\s]+block[\s]+untagged[\s]+mb15"[\s]+id=\'qiushi_tag_(\d+?)\'>'
这么写为何读到id都是1
回复 支持 反对

使用道具 举报

0

主题

5

帖子

5

积分

贫民

积分
5
python_jack 发表于 2016-7-28 17:58:42 | 显示全部楼层
谢谢楼主分享,待会吃完饭看看
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

快速回复 返回顶部 返回列表