找回密码
 立即注册

扫一扫,访问微社区

QQ登录

只需一步,快速开始

查看: 4798|回复: 2

[代码与实例] python2.7.6 和BeautifulSoup4.4.1 抓取糗事百科,带评论

1

主题

1

帖子

1

积分

贫民

积分
1
pythonLearner 发表于 2015-12-14 12:22:30 | 显示全部楼层 |阅读模式
  1. __author__ = 'KS'
  2. # -*- coding: utf-8 -*-

  3. import urllib2
  4. import re
  5. from bs4 import BeautifulSoup


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


  13. # 文章地址
  14. articleUrl = "http://www.qiushibaike.com/textnew/page/%d"
  15. # 评论地址
  16. commentUrl = "http://www.qiushibaike.com/article/%s"
  17. page = 0
  18. while True:
  19.     getFromCustomer = raw_input("next page ? print Enter key to continue or 'exit' to stop\n")
  20.     if getFromCustomer == "exit":
  21.         break
  22.     page += 1
  23.     urlJoin = articleUrl % page
  24.     print urlJoin
  25.     articlePage = getContentOrComment(urlJoin)
  26.     soupArticle = BeautifulSoup(articlePage, 'html.parser')
  27.     # print soup.prettify()
  28.     articleFloor = 1
  29.     for string in soupArticle.find_all(attrs="article block untagged mb15"):
  30.         commentId = str(string.get('id')).strip()[11:]
  31.         print "\n"
  32.         print articleFloor, ".", string.find(attrs="content").get_text().strip()
  33.         articleFloor += 1
  34.         commentPage = getContentOrComment(commentUrl % commentId)
  35.         soupComment = BeautifulSoup(commentPage, 'html.parser')
  36.         commentFloor = 1
  37.         for comment in soupComment.find_all(attrs="body"):
  38.             print "     ", commentFloor, "楼回复:", comment.get_text().strip()
  39.             commentFloor += 1
复制代码


回复

使用道具 举报

1

主题

7

帖子

7

积分

贫民

积分
7
wangcj456 发表于 2016-8-26 15:29:43 | 显示全部楼层
学习了,谢谢楼主
回复 支持 反对

使用道具 举报

5

主题

165

帖子

165

积分

版主

Rank: 7Rank: 7Rank: 7

积分
165

热心会员突出贡献优秀版主荣誉管理

mongo 发表于 2016-8-30 16:58:56 | 显示全部楼层
学习了.{:8_204:}
回复

使用道具 举报

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

本版积分规则

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