浏览器下载xpath插件
chrome插件下载
提取码:5iex
python安装lxml库
pip install lxml -i https://pypi.douban.com/simple
etree.parse() 解析本地文件
html_tree = etree.parse(‘xxx.html’)
etree.HTML() 服务器响应文件
html_tree = etree.HTML(response.read().decode(‘utf-8’))
html_tree.xpath(xpath路径)
路径获取
import urllib.request
from lxml import etree
def create_request(page):
if (page == 1):
url = 'https://sc.chinaz.com/tupian/meinvtupian.html'
else:
url = 'https://sc.chinaz.com/tupian/meinvtupian_' + str(page) + '.html'
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/537.36'
}
request = urllib.request.Request(url=url,headers=headers)
return request
def get_content(request):
response = urllib.request.urlopen(request)
content = response.read().decode('utf-8')
return content
def down_load(content):
# 解析网页源码
tree = etree.HTML(content)
name_list = tree.xpath('//div[@id="container"]//a/img/@alt')
src_list = tree.xpath('//div[@id="container"]//a/img/@src')
# 下载图片到本地
for i in range(len(name_list)):
name = name_list[i]
src = src_list[i]
url = 'https:' + src
urllib.request.urlretrieve(url=url,filename='./images/'+name+'.jpg')
if __name__ == '__main__':
start_page = int(input("请输入起始页码:"))
end_page = int(input("请输入结束页码:"))
for page in range(start_page, end_page + 1):
request = create_request(page)
content = get_content(request)
down_load(content)
文章推荐:https://blog.csdn.net/luxideyao/article/details/77802389
无