import urllib.request
import os
def url_open(url):
head={}
head['User-Agent']=' Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.116 Safari/537.36'
req=urllib.request.Request(url,head)
response=urllib.request.urlopen(req)
html=response.read()
return html
#找图片对应的规律
def get_page(url):
html=url_open(url).decode('utf-8')
a=html.find('current')+9
b=html.find('<',a)
return html[a:b]
#寻找图片地址
def find_imgs(url):
html=url_open(url).decode('utf-8')
img_addrs=[]
a=html.find('img src=')
while a!=-1:
b=html.find('.jpg',a,a+255)
if b!=-1:
img_addrs.append(html[a+9:b+4])
else:
b=a+9
a=html.find('img src=',b)
return img_addrs
#保存图片
def save_imgs(folder,img_adders):
for each in img_addrs:
filename=each.split('/')[-1]
with open(filename,'wb') as f:
img=url_open(each)
f.write(img)
def download(folder='照片合集',pages=30):
os.mkdir(folder)
os.chdir(folder)
url='https://www.7160.com/xingganmeinv/'
page_num=int(get_page(url))
for i in range(pages):
page_num+=i
page_url=url+'list_3_'+str(page_num)+'.html'
#img是将图片地址保存为列表
img_addrs=find_imgs(page_url)
save_imgs(folders,img_addrs)
#测试函数
if __name__=='__main__':
download()
相似问题