一、目标
爬取500px图片并保存
目标网址:https://500px.com.cn/community/discover
二、分析
2.1 网站分析:
经过研究发现该网站没有点击下一页的按钮,然后往下拖动下拉条直到最后,会自动刷新出新的内容,基本可以得出该网页是动态刷新的。
或者ctrl+U 打开页面源码,复制粘贴一张图片的地址,在源码中找不到对应的地址,也可以判断该页面为动态加载的。
2.2 反爬分析:
相同的IP爬取大量的图片可能会被反爬(频率反爬),故需要采用UA池
三、注意点:
1.一定要选取正确的网页接口,接口一般包含该网页的全部信息
2.找到接口并找到每张图片的对应地址后,发现该地址并不完整需要我们手动拼接一部分内容,此处为"!p4"或者"!a1"。
四、代码
import uuid
import requests
from fake_useragent import UserAgent
class Spider_Photoes(object):
def __init__(self):
ua = UserAgent()
self.url = 'https://500px.com.cn/discover/rating?resourceType=0,2&category=&orderBy=rating&photographerType=&startTime=&page={}&size=20&type=json'
self.headers = {
'User - Agent': ua.random
}
def get_etree(self,url):
response = requests.get(url,headers=self.headers)
html = response.json()
return html
def get_img_url(self,html):
img_list = html.get('data')
for img in img_list:
filename = uuid.uuid4().hex+'.jpg'
img_url = img.get('url').get('baseUrl')+'!a1'
print(img_url)
response = requests.get(img_url,headers=self.headers)
with open('./picture/'+filename,'wb') as w:
w.write(response.content)
w.flush()
def main(self):
start_page = int(input('输入起始页码:'))
end_page = int(input('输入结束页码:'))
for page in range(start_page, end_page + 1):
print('第%d页'%page)
url = self.url.format(page)
html = self.get_etree(url)
self.get_img_url(html)
if __name__ == '__main__':
sp = Spider_Photoes()
sp.main()