版权声明:转载请附上链接 https://blog.csdn.net/python_neophyte/article/details/82534621
爬虫实现简单下载壁纸,自己想的话可以调用api做个小翻译器,然后拼装起来。
先上思路:www.pexels.com是个高质量的找图网站,先试一试其网址的变化规律,搜索之后发现规律如下
www.pexels.com/search/xxxxxxxx,也就是url与search和搜索内容拼装起来,接下来利用xpath
或者美丽汤(BeautifulSoup)在页面上分析出规律,按F12,然后找出图片对应的源代码。
接下来就是利用requests库进行爬取,然后用基本的文件操作方法写入数据,保存在预设或者
临时创立的文件夹下。
下面上代码
关于user_key的声明:
请去官网申请账号后登陆,就可以得到user_key
百度搜索不到,谷歌才行,这里直接上网址 https://howtospeak.3scale.net/
#!/usr/bin/python3
#-*-coding:UTF-8-*-
import requests
from bs4 import BeautifulSoup
from fake_useragent import UserAgent
import random
import json
ua = UserAgent()
headers = {'User-Agent': ua.random}
urls ='https://www.pexels.com/search/'
#api调用howtospeak翻译器
word = input('请输入想要下载的图片类型:')
url='http://howtospeak.org/api/e2c?user_key=这一段请去howtospeak官网自主申请%20¬rans=0&text={}'.format(word)
response = requests.get(url,headers = headers)
json_data = json.loads(response.content.decode('utf-8'))
english_version = json_data['english']
c_url = urls + english_version + '/' #拼装url,翻译过来的版本即想要搜索的内容
#获取拼装后的url的每个图片的地址,并放在link列表里
web_data = requests.get(c_url, headers = headers)
soup = BeautifulSoup(web_data.text,'lxml')
images = soup.select('article > a > img')
link = []
for image in images:
photo_link = image.get("src")
link.append(photo_link)
#创建目录(也可以自己在磁盘先创建,或者选取现成的)
path = 'd://pexels/'
#下载图片
count = 1
for item in link:
print('正在下载第' +str(count) + '张图片...')
data = requests.get(item, headers = headers)
with open(path + item.split('?')[0][-12:], 'wb') as f:
f.write(data.content)
count += 1
print('图片下载完毕啦。')
最近比较忙,以后有空来补充细节!顺便吐槽下煎蛋网源码加密,晕了,浪费好多时间。