- 导入模块并判断所下载图片是否存在文件夹
import requests
from lxml import etree
import os
if not os.path.exists("e:/图片"):
os.mkdir("e:/图片")
2.数据获取【每张图片url及图片名称】
url = "http://www.jkl.com.cn/cn/phoLis.aspx"
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.135 Safari/537.36'
}
for i in range(1,4):
date = {
'__EVENTTARGET':'AspNetPager1',
'__EVENTARGUMENT': i
}
response = requests.get(url, headers=headers,params=date).text
html = etree.HTML(response)
img_url = html.xpath('//div[@class ="proLis"]//img/@src')
img_url1 = ["http://www.jkl.com.cn"+i for i in img_url]
img_name = html.xpath('//div[@id ="list"]//a//span/text()')
img_name1 = [a.strip() for a in img_name]
img_name1 = [b.replace("——", "") for b in img_name1]
dt1 = dict(zip(img_name1, img_url1))
3.获取每张图片的二进制数据并保存到本地
for n,u in dt1.items():
# print(u)
response = requests.get(u,headers=headers).content
houzhui = u.split('.')[-1]
path = f"e:/图片/{n}."+ houzhui
with open(path, 'wb') as f:
f.write(response)
print(n,'下载完成!')
#考虑到块代码不能完整体现缩进问题,附完整代码
import requests
from lxml import etree
import os
if not os.path.exists("e:/图片"):
os.mkdir("e:/图片")
url = "http://www.jkl.com.cn/cn/phoLis.aspx"
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.135 Safari/537.36'
}
for i in range(1,4):
date = {
'__EVENTTARGET':'AspNetPager1',
'__EVENTARGUMENT': i
}
response = requests.get(url, headers=headers,params=date).text
html = etree.HTML(response)
img_url = html.xpath('//div[@class ="proLis"]//img/@src')
img_url1 = ["http://www.jkl.com.cn"+i for i in img_url]
img_name = html.xpath('//div[@id ="list"]//a//span/text()')
img_name1 = [a.strip() for a in img_name]
img_name1 = [b.replace("——", "") for b in img_name1]
# print(img_url1)
dt1 = dict(zip(img_name1, img_url1))
for n,u in dt1.items():
# print(u)
response = requests.get(u,headers=headers).content
houzhui = u.split('.')[-1]
path = f"e:/图片/{n}."+ houzhui
with open(path, 'wb') as f:
f.write(response)
print(n,'下载完成!')