美文网首页
Python-针对懒加载技术爬取图片

Python-针对懒加载技术爬取图片

作者: 大森森_ | 来源:发表于2020-04-21 22:38 被阅读0次

import urllib.request
import urllib.parse
from lxml import etree
import time

def handle_request(url,page):
#由于第一页和后面的页码规律不一样,所以要进行判断#
if page==1:
url=url.format('')
else:
url=url.format('_'+str(page))

print(url)
    
headers={
    "User-Agnet":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36"
}
   
request=urllib.request.Request(url=url,headers=headers)
return  request 

解析内容,并且下载图片#

def parse_content(content):
tree=etree.HTML(content)
#懒加载,用到的时候再加载#
image_list=tree.xpath('//div[@id="container"]/div/div/a/img/@src2') #注意懒加载代码#
print(image_list)
print(len(image_list))
#遍历列表,依次下载图片#
for image_src in image_list:
download_image(image_src)

def download_image(image_src):
dirpath='文件保存路径'
#创建一个文件夹#
if not os.path.exists(dirpath):
os.mkdir(dirpath)
#创建文件名#
filename=os.path.basename(image_src)
#创建图片路径#
filepath=os.path.join(dirpath,filename)
#发送请求,保存图片#
headers={
"User-Agnet":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36"
}
request=urllib.request.Request(url=image_src,headers=headers)
response=urllib.request.urlopen(request)
with open(filepath,'wb') as fp:
fp.write(response.read())

def main():
url="http://sc.chinaz.com/tag_tupian/yazhoumeinv{}.html"
start_page=int(input("请输入起始页码:"))
end_page=int(input("请输入结束页码:"))
for page in range(start_page,end_page+1):
request=handle_request(url,page)
content=urllib.request.urlopen(request).read().decode()
parse_content(content)
time.sleep(2)

if name=='main':
main()

相关文章

网友评论

      本文标题:Python-针对懒加载技术爬取图片

      本文链接:https://www.haomeiwen.com/subject/kuzmihtx.html