免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 1535 | 回复: 0
打印 上一主题 下一主题

大家帮我看看为毛urllib2 无法read出数据 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2017-05-05 16:04 |只看该作者 |倒序浏览
我的代码如下,目的是爬取某网站上的数据,但是,我发现使用urllib2.open()打开网页后,无法读取内容,即:read()为空。
但是urlopen已经执行成功,并且返回code:200
我不知道是不是因为用爬虫爬取数据,所以他不给返回了,跪请大神指点

  1. # encoding: utf-8
  2. import json
  3. import urllib
  4. import urllib2
  5. import re
  6. import sys
  7. reload(sys)
  8. sys.setdefaultencoding( "utf-8" )

  9. def getproductID(productID, page):
  10.     url = "https://club.jd.com/comment/productPageComments.action?productId=" + productID + "&score=0&sortType=5&page=" + str(page) + "&pageSize=10&isShadowSku=0"
  11.     user_agent = 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.81 Safari/537.36'
  12.     headers = {'User-Agent': user_agent}
  13.     req = urllib2.Request(url)
  14.     req.add_header('User-Agent', user_agent)
  15.     try:
  16.         response = urllib2.urlopen(req)
  17.     except urllib2.URLError, e:
  18.         if hasattr(e,"reason"):
  19.             print "Page %d Failed to connect the server!" % page
  20.             print "The reason is: %s" % e.reason
  21.             return
  22.         elif hasattr(e, 'code'):
  23.             print "Error code is: %s" % e.code
  24.             return

  25.     data = response.read()
  26.     html = data.decode("gbk", "ignore").encode("utf-8")
  27.     comment_file = "comments.txt"

  28.     if data:
  29.         j = json.loads(html)
  30.         if len(j["comments"]) == 0:
  31.             print "Job is done!"
  32.             print "Total of pages are: %d" % page
  33.         else:
  34.             for i in range(len(j["comments"])):
  35.                 with open(comment_file, 'a') as fh:
  36.                     fh.write(j["comments"][i]["nickname"] + ':')
  37.                     fh.write(j["comments"][i]["content"] + '\n')
  38.     else:
  39.         with open("tmp.txt", 'a') as tmp:
  40.             tmp.write(str(page) + ": " + data + '\n')
  41.         with open("tmp_comment.txt", 'a') as tmp:
  42.             tmp.write(str(page) + ": " + html + '\n')
  43.         with open(comment_file, 'a') as fh:
  44.             fh.write('Page: ' + str(page) + 'Code: ' + str(response.getcode()) + '\n')
  45.             #fh.write(response.info())
  46.             fh.write('\n')



  47. if __name__ == '__main__':
  48.     for i in range(100000):
  49.         getproductID('2967927', i)
复制代码


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

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP