|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
本帖最后由 Prusuit 于 2021-12-29 11:58 编辑
- import urllib.request
- import chardet
- import os
- import random
- import easygui
- def build_opener():
- # 这些IP都是我在网上搜的,检查的时候发现许多都用不了,所以在主函数上把这个函数注释掉了,大家有好的IP可以自己切换
- ip_list1 = ['210.26.124.143:808', '106.75.226.36:808', '125.62.26.197:3128', '120.92.74.189:3128',
- '113.200.56.13:8010']
- proxy_support = urllib.request.ProxyHandler({'https': random.choice(ip_list1)})
- opener = urllib.request.build_opener(proxy_support)
- urllib.request.install_opener(opener)
- def find_picture(html):
- """此函数用来找到网页中所有照片的网站,并返回一个携带有所有网址的代码"""
- picture_list = []
- a = 0
- b = 0
- while b != -1:
- a = html.find('img src=', a) + 9
- if a == 8:
- break
- b = html.find('"', a)
- picture_list.append(f' http:{html[a:b]}')
- a = b + 100
- return picture_list
- def find_next_web(html, number):
- """此函数返回一个含有已经解码过的网页的列表"""
- web_list = []
- while number > 1:
- a = html.find("current-comment-page") + 43
- b = html.find(""", a)
- the_url = "http:" + html[a:b]
- req = urllib.request.Request(the_url)
- html = urllib.request.urlopen(req).read()
- encode = chardet.detect(html)['encoding']
- html = html.decode(encode)
- web_list.append(html)
- # 设立循环限制
- number -= 1
- return web_list
- def save_picture(picture_list):
- """此函数接收一个含有照片网站的列表,将所有照片保存在指定位置"""
- # 选择所要保存图片的位置
- target = easygui.diropenbox("请指定您要保存的地址")
- # 将工作目录切换到指定位置上,并创立一个文件夹,用来存放照片
- os.chdir(target)
- os.mkdir('girls_pictures')
- os.chdir('girls_pictures')
- n = 0
- for each in picture_list:
- response = urllib.request.urlopen(each)
- picture = response.read()
- with open(f'girl_{n}.jpg', 'wb') as f:
- f.write(picture)
- n += 1
- def download_pictures(url):
- """主程序,选择需要下载多少页,并选择图片保存位置"""
- download_page = int(easygui.enterbox("请问您需要下载多少页面的图片"))
- picture_list = []
- # 建立虚拟ip,防止同一个IP过于频繁访问被封
- # build_opener()
- # 添加请求头中的“User-Agent"来模拟浏览器访问
- headers = {"User-Agent": 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)'
- ' AppleWebKit/537.36 (KHTML, like Gecko) '
- 'Chrome/96.0.4664.110 Safari/537.36'}
- # 访问最外层网站,再将其解码
- req = urllib.request.Request(url, headers=headers)
- html = urllib.request.urlopen(req).read()
- encode = chardet.detect(html)['encoding']
- html = html.decode(encode)
- # 通过find_picture()函数找到其中照片地址存放到一个列表中
- for each1 in find_picture(html):
- picture_list.append(each1)
- # 循环打开下一层页面, 并将所有图片地址都存放到picture_list列表中
- for each_html in find_next_web(html, download_page):
- for each in find_picture(each_html):
- picture_list.append(each)
- # 将已经收集到的照片地址一个一个打开并存放指定文件夹中
- save_picture(picture_list)
- if __name__ == "__main__":
- url = 'https://jandan.net/girl/'
- download_pictures(url)
复制代码 |
|