最底完整代码更新,支持手动输入搜索关键字,下载任意想下载的壁纸
抓网站壁纸!
开搞!!!
完整代码直接下拉到底部!!
1.首先引入需要的库,需要先下载好
import requests #请求处理URL资源
from bs4 import BeautifulSoup # 处理标签文本
import time #延时
2.准备url
想要抓取《瑞克和莫蒂》分类下的桌面壁纸,就复制这页链接
# 瑞克和莫蒂分类的链接
url = "https://wall.alphacoders.com/by_sub_category.php?id=233584&name=%E7%91%9E%E5%85%8B%E5%92%8C%E8%8E%AB%E8%92%82+%E5%A3%81%E7%BA%B8&lang=Chinese"
# 下面的链接下面会说
url_download = "https://api.alphacoders.com/content/get-download-link"
3.获取到url返回资源
resp = requests.get(url) # 请求
resp.encoding = 'utf-8' # 处理乱码
4.拿到返回代码给BeautifulSoup解析,我们用BeautifulSoup来处理想要的数据
page = BeautifulSoup(resp.text,"html.parser")
5.查看网页源代码找到下载的方式是:通过点击下载按钮调用函数,获取到图片
下载路径是:
url_download = "https://api.alphacoders.com/content/get-download-link"
入参是:点击按钮span标签上带的属性值
6.通过观察页面代码发现,可以通过class名为download-button过滤得到这个span
# 拿到所有span点击按钮
span = page.find_all("span",class_="download-button")
7.准备入参和下载
调用步骤5的链接,发现返回的还是链接,复制到浏览器打开,图片开始下载,原来这个才是真正的下载链接,所以再请求,返回的数据就是图片了
for it in span:
data_id = it.attrs['data-id']
data_type = it.attrs['data-type']
data_server = it.attrs['data-server']
# print(data_id)
#准备请求入参
data = {
"content_id": data_id,
"content_type": "wallpaper",
"file_type": data_type,
"image_server": data_server
}
# 获取下载图片的链接
download_resp = requests.post(url_download,data=data)
download_link = download_resp.json()['link']
# print(download_link)
# 下载
img_download_resp = requests.get(download_link)
img_name = data_id
# 储存图片
with open("alphacoder_桌面/"+img_name+'.jpg',mode="wb") as f:
f.write(img_download_resp.content)
time.sleep(1) # 暂停1秒,防止封禁
f.close() #关闭文件
附上完整代码 ,运行python xxx.py即可食用~~(xxx替换为文件名)
import requests
from bs4 import BeautifulSoup
import time
print("请输入搜索关键字,按回车结束")
keyvalue = input()
print('开始下载'+keyvalue+'的壁纸...')
url = "https://wall.alphacoders.com/search.php?search="+keyvalue
url_download = "https://api.alphacoders.com/content/get-download-link"
resp = requests.get(url)
resp.encoding = 'utf-8' # 处理乱码
# print(resp)
# 拿到页面代码
page = BeautifulSoup(resp.text,"html.parser")
span = page.find_all("span",class_="download-button")
# print(span)
for it in span:
data_id = it.attrs['data-id']
data_type = it.attrs['data-type']
data_server = it.attrs['data-server']
# print(data_id)
#准备请求入参
data = {
"content_id": data_id,
"content_type": "wallpaper",
"file_type": data_type,
"image_server": data_server
}
# 获取下载图片的链接
download_resp = requests.post(url_download,data=data)
download_link = download_resp.json()['link']
# print(download_link)
# 下载
img_download_resp = requests.get(download_link)
img_name = data_id
# 储存图片
with open("alphacoder_桌面/"+img_name+'.jpg',mode="wb") as f:
f.write(img_download_resp.content)
time.sleep(1) # 暂停1秒,防止封禁
if(span):
f.close()
else:
print('没有'+keyvalue+'的壁纸')
print("完成!")