0
点赞
收藏
分享

微信扫一扫

Python《第一次爬虫遭遇反盗链(上)》


今天想爬取下往上很多人都爬取过的https://www.mzitu.com/ 。
结果很尴尬,只能很浅显地爬取一些首页图片,因为遭遇到了反盗链。

鉴于图片过于那啥,其实我就来搞学习的,也不是什么LSP,老司机之类的,因此,在此就不做解析了哈哈哈,大家自行去看网站的首页吧啊。

因为遭遇到了反盗链,所以浅显地把首页上哪些分页的照片爬取下来就得了。

这是故事上,下一次我将试图突破反盗链,如果成功的话,就会补充上。

import os
import requests
from bs4 import BeautifulSoup

rootrurl = 'https://www.mzitu.com/'
save_dir = 'D:/estimages/'
no_more_pages = 'END'
max_pages = 10

# 这是一个集合,不能重复,也就是不能重复下载图片
image_cache = set()
index = len(image_cache)

headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36",
"Referer": "https://www.mzitu.com/"
}

def getNextPageUrl(html):
ahref = html.find('a', {'class': 'next page-numbers'}) # 找到导航条的位置,获得下一个连接网页的位置
if ahref is None:
print('no more page')
return no_more_pages
else:
return ahref.get('href')



def saveImgs(html, mainidx):
lis = html.find('ul', {'id': 'pins'}).find_all('li') # 找到导航条的位置,获得下一个连接网页的位置
subidx = 1
for link in lis:
# step 1: save this cover image, and create the folder.
a = link.find('a')
href = a.get('href')
img = a.find('img').get('data-original')
print('img: ' + img)
# tag = '{}{}/{}/'.format(save_dir, mainidx, subidx)
tag = '{}{}/'.format(save_dir, mainidx)

if not os.path.exists(tag):
os.makedirs(tag)

with open(
'{}/{}'.format(tag, "coverImg_" + img.split("/")[-1]), 'wb') as jpg: # 请求图片并写进去到本地文件
jpg.write(requests.get(img).content)
if img not in image_cache:
image_cache.add(img)

# step 2: enter the mew page to save deeply.
# 防盗链,我暂时没法解决。。。。。。
# deepSaveImgs(href, tag) #深度搜索该图片组

subidx = subidx + 1



if __name__ == '__main__':
url = rootrurl
idx = 1
while 1:
print("next page: " + url)
html = BeautifulSoup(requests.get(url, headers=headers).text, features="html.parser")
saveImgs(html, idx) # 处理当前浏览页面

if idx >= max_pages:
break
idx = idx + 1

url = getNextPageUrl(html) # 获得下一个浏览页
if url == no_more_pages:
break

效果图如下啊:

不敢展开展示啊。。。。。。

Python《第一次爬虫遭遇反盗链(上)》_Python


举报

相关推荐

0 条评论