day_5.10py 爬妹子图片 mm131

时间:2023-03-09 15:34:39
day_5.10py 爬妹子图片  mm131
  
  #目前学的爬虫还有潭州教育的直播课,都是千篇一律的requests urllib 下面这个也是,还没有我后面的下载网易云歌单爽来都用到多线程了不过可以用协程,完全异步
1 #!/usr/bin/env/python
#-*-coding:utf-8-*- '''
2018-5-9 20:16:57
下次查明原因
不会知道为什么报错
2018-5-10 19:32:39开始重新看视频
把那个代码删了重新编码一下
一切运行成功
代码没错应该是网站封我ip了 还是很不错的
py爬虫还是很强大的
2018-5-10 21:12:37
'''
import requests #这个是访问http协议的模块
from urllib.request import urlopen,urlretrieve,urljoin,Request
import time #尽量来点休眠
import re url = 'http://www.mm131.com/xinggan/' def get_img(url,path,ref):
#url: jpg地址图像真正的地址
#path: 图像下载之后保存的路径
#ref: 图像的ref值
headers = {
'User-Agent':'Mozilla/5.0 (Windows NT 6.1; rv:2.0.1) Gecko/20100101 Firefox/4.0.1',
'Referer':ref
}
req = Request(url=url,headers=headers)
res = urlopen(req).read()
with open(path,'wb') as fp:
fp.write(res) def download(home_url):
#一级列表页面
html = requests.get(home_url).content.decode('gbk')
urls = re.findall('list_6_[0-9]+.html',html) #相对路径
urls = [urljoin(home_url,url) for url in urls] # 二级列表页
#http://www.mm131.com/qingchun/3982.html
urls_2 =[]
for url in set(urls):#从一级列表页下面去出来每一个链接
html = requests.get(url).content.decode('gbk')
for i in re.findall('http://www.mm131.com/xinggan/[0-9]+.html',html):
urls_2.append(i)
print(urls_2)
# 三级列表页
#3961_3.html
urls_3 = []
for url in set(urls_2):
html = requests.get(url).content.decode('gbk')
for i in re.findall('[0-9_]+.html',html):
urls_3.append(i) pic_url = {}#key值唯一.不需要额外去重
# 字典中:
# key: 图像地址
# value: Referer值
# ..jpg:...3333_1.html
# 从这个一个个的图片展示页面下提取真正的图片地址.jpg
for url in set(urls_3):
# http://img1.mm131.me/pic/3961/2.jpg
# http://img1.mm131.me/pic/3961/3.jpg
# http://img1.mm131.me/pic/[0-9]+/[0-9]+.jpg
html = requests.get(url).content.decode('gbk')
try:
i = re.findall('http://img1.mm131.me/pic/[0-9]+/[0-9]+.jpg', html)[0]
except:
print("[Error] 无效的链接:", url)
else:
pic_url[i] = url
# 从展示页面下,右键是可以看到的
# 但是直接通过url链接去访问就是不行的
# 防盗链
index = 0
for url in pic_url:
# key: 下载地址
# value: ref值
print('[+] 当前下载%d张:%s' % (index, url))
get_img(url=url, path=str(index) + '.jpg', ref=pic_url[url])
index += 1 download(url)