1. import requests
  2. from lxml import etree
  3.  
  4. headers={
  5. "User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:71.0) Gecko/20100101 Firefox/71.0",
  6. "Referer":"https://www.mzitu.com/",
  7. }
  8. response = requests.get("https://www.mzitu.com/" , headers=headers) #获得网页源码
  9. # print(response.text) 查看是否录入网页源码
  10.  
  11. html = etree.HTML(response.text)
  12. #response.text为字符串类型
  13. #etree.HTML()可以用来解析字符串格式的HTML文档对象,将传进去的字符串转变成_Element对象。
  14. #作为_Element对象,可以方便的使用getparent()、remove()、xpath()等方法。
  15.  
  16. src_list = html.xpath(\'//img[@class="lazy"]/@data-original\')
  17. alt_list = html.xpath(\'//img[@class="lazy"]/@alt\')
  18. #xpath返回一个列表
  19.  
  20. for src,alt in zip(src_list,alt_list):
  21. response = requests.get(src, headers=headers)
  22. FileName = "img\\" + alt + ".jpg"
  23. print("正在保存图片:" + FileName)
  24. with open(FileName,"wb") as p:
  25. #二进制写入,说明response内容为二进制
  26. #text 返回的是unicode 型的数据,一般是在网页的header中定义的编码形式。content返回的是bytes,二进制型的数据。
  27. p.write(response.content)

   加油加油加油!!!

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