Project-GetPhotoFromY

概述

  这是一个简单的python爬虫脚本,爬取的目标是Y站的动漫图片。提前说明的是,只建议用此文进行学习,不建议对Y站进行爬虫,因为Y站服务器不是很强,进行爬取会影响其他用户正常访问,我也是测试运行正常后就停止运行了,只爬取了两张图片。

实现思路

  这个爬虫脚本的实现比较简单,首先查看网站第一页地址如下:

1
https://yande.re/post?page=1

  若想爬取第$i$页内容,仅需要进行简单的字符串拼接即可:

1
url = 'https://yande.re/post?page=' + str(i)

  之后检测页面源代码,发现想爬取的图片URL被放到如下格式语句中:

1
<a class="directlink largeimg" href="https://files.yande.re/image/3ca8db344a7ddd13727804aaf6622244/yande.re%20436280%20feet%20maora%20pantyhose%20seifuku%20sweater.jpg">

  运用一个正则表达式提取URL:

1
photo_lise = re.findall('<a class="directlink largeimg" href="(.*?)">',html1_1.text)

  其中”(.*?)”处为所需要的URL,而”re.findall()”方法则返回符合条件的对象所组成的一个列表。之后再利用列表中的URL将图片下载到本地即可。

代码

  我将实现过程封装起来,在函数中输入想爬取的页码数即可,完整代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import requests
import os
import re

# get photo from Y,page is the num of page you want
def getphoto(page):
url = 'https://yande.re/post?page=' + str(page)
header = {'User-Agent':'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36'}
html1_1 = requests.get(url,headers=header)
photo_lise = re.findall('<a class="directlink largeimg" href="(.*?)">',html1_1.text)
numOfPhoto = len(photo_lise)

for i in range(0,numOfPhoto):
print i
image_url = photo_lise[i]
r = requests.get(image_url)
binfile = open(str(i)+'jpg',"wb")
binfile.write(r.content)
binfile.close()
print 'finish' + str(i)

if __name__ == '__main__':
getphoto(1)

  运行结果如下:

1
2
3
4
5
6
7
8
python getPhoto.py 
0
finish0
1
finish1
2
^Z
[2]+ 已停止 python getPhoto.py

  在成功爬取两张后强制停止了脚本。

小结

  Y站我对不起你Orz