使用python的requests库爬取网页时,获取文本一般使用text方法,如果要获取图片并保存要用content

举个栗子,爬煎蛋网的图:

  1. #!/usr/bin/env python
  2. #-*- coding:utf-8 -*-
  3. import requests
  4. import re
  5. import os
  6. url="http://jandan.net/ooxx"
  7. s = requests.session()
  8. header_jandan={\'Host\': \'jandan.net\',
  9. \'Connection\': \'keep-alive\',
  10. \'Cache-Control\': \'max-age=0\',
  11. \'Upgrade-Insecure-Requests\': \'1\',
  12. \'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\',
  13. \'Accept\': \'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8\',
  14. \'Referer\': \'http://jandan.net/ooxx\',
  15. \'Accept-Encoding\': \'gzip, deflate, sdch\',
  16. \'Accept-Language\':\'zh-CN,zh;q=0.8\'}
  17. resp = s.get(url,headers=header_jandan,timeout=10)
  18. if len(resp.text) < 1500:
  19. resp2 = s.get(url,headers=header_jandan,timeout=10)
  20. text=resp2.text
  21. else:
  22. text=resp.text
  23. #print rn.text
  24. img_url=re.findall(ur\'(?<=\<img src\=").*?(?=\")\',text)
  25. d=os.getcwd()
  26. for i in img_url:
  27. ret=i.split("/")
  28. file = ret[-1]
  29. #print file
  30. if i.find("http") == -1:
  31. url_img="http:"+i
  32. r_img=s.get(url_img,headers=header_jandan,timeout=10)
  33. open(os.path.join(d,file), \'wb+\').write(r_img.content)
  34. print "write %s" % file

考虑到如果图片很大,获取需要时间,设置timeout超时避免内容取不完整。

写文件内容为r_img.content

打开文件的方式使用wb+,二进制文件覆盖方式写入。

版权声明:本文为taurusfy原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://www.cnblogs.com/taurusfy/p/7158801.html