from lxml import etree
import requests
url = "https://www.youmeitu.com/meinv/"
headers = {
"user-agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.45 Safari/537.36"
}
resp = requests.get(url,headers=headers)
tree = etree.HTML(resp.text)
result = tree.xpath("/html/body/div[3]/div[5]/ul/li/a/img/@src")
for i in result:
resp2 = requests.get(i,headers=headers)
name = i.split("/")[4].split("?")[0]
filename = f"图片文件夹\{name}"
with open(filename,mode="wb") as f:
f.write(resp2.content)
print("over!")
问题总结:
1.要获取html中的标签属性值,要用./@属性
2.etree.HTML的(HTML)是大写
3.filename = f'图片文件夹\{i.split("/")[4].split("?")[0]}' 外圈要用单引号,因为中间已经用过双引号,否则报错SyntaxError: f-string: unmatched '('
最终成果
一堆美女图片