安装库 pip install lxml
pip install requests
以下是代码 ?
import os
import requests
from lxml import etree
#下载
def download_img(imgurl,index):
try:
rsp = requests.get(imgurl)
if rsp.status_code == 200:
content = rsp.content
if not os.path.isdir("./img"):
os.makedirs("./img")
# 注意下面open里面的mode是"wb+", 因为content的类型是bytes
imgpath = "./img/"+str(index) +".jpg"
with open(imgpath, "wb+") as f:
f.write(content)
#return str(content)
except Exception as err :
print("load img err=",err)
url = "https://www.toopic.cn/"
req = requests.get(url)
req.encoding = "utf-8"
data = req.text
html = etree.HTML(data)
new_data = html.xpath('//a/img/@data-original')
#imgName_data = html.xpath('//a[@title]')
for index in range(len(new_data)):
#print("地址是: %s%s" %(url,new_data[index]))
imgurl = url+new_data[index]
download_img(imgurl,index)
?
|