异常报错
Traceback (most recent call last):
File "H:/NewProject/Taylor/Requests/paQu_03.py", line 31, in <module>
with open(img_path, 'wb') as fp:
FileNotFoundError: [Errno 2] No such file or directory: 'picLibs//uploads/allimg/210417/231238-16186723587a5b.jpg.jpg'
原代码
import requests
import os
from lxml import etree
# 需求:解析下载图片数据
url = 'https://pic.netbian.com/4kmingxing/'
headers = {
'user-agent': 'Mozilla/5.0 (Windows NT 10.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.93 Safari/537.36'}
response = requests.get(url=url, headers=headers)
# 手动设定响应数据的编码格式:
# respones.encoding = 'utf-8'
page_text = response.text
# page_text = requests.get(url=url,headers=headers).text
# 数据解析:src的属性值 alt属性
tree = etree.HTML(page_text)
li_list = tree.xpath('//div[@class="slist"]/ul/li')
# 创建一个文件夹
if not os.path.exists('./picLibs'):
os.mkdir('./picLibs')
for li in li_list:
img_src = 'https://pic.netbian.com' + li.xpath('./a/img/@src')[0]
img_name = li.xpath('./a/img/@src')[0] + '.jpg'
# 通用处理中文乱码的解决方案
# img_name = img_name.encode('iso-8859-1').decode('gdk')
# print(img_name,img_src)
# 请求图片进行持久化存储
img_data = requests.get(url=img_src, headers=headers).content
img_path = 'picLibs/' + img_name
with open(img_path, 'wb') as fp:
fp.write(img_data)
print(img_name, '下载成功!!!')
# root_dir = os.path.abspath('.')
# case_path = root_dir+"/picLibs"
# print(case_path)