今天想给我的电脑里面多加点壁纸,但是嫌弃一个个保存太慢,于是想着写个爬虫直接批量爬取,正好我也刚刚学完爬虫。
我们要爬取一个壁纸网站 http://www.netbian.com/weimei/index.htm 。
需要用到的库是reqursts和BeautifulSoup,这两个库我就不多介绍了
reqursts文档快速上手 — Requests 2.18.1 文档 (python-requests.org)
BeautifulSoup文档Beautiful Soup 4.4.0 文档 — beautifulsoup 4.4.0q 文档
如果有不懂的可以参考一下
现在开始爬取
我们先分析一下思路,第一步拿主页面源码 ,第二步通过url拿到子页面的内容地址, 第三步下载图片。我们先看一下网站结构,右键打开页面源代码(这是部分源码),图中可以看到图片标题和url,还有我们需要的各个节点
#引入需要的库
import requests
from bs4 import BeautifulSoup
url = "http://www.netbian.com/weimei/index.htm"
resp = requests.get(url)
#resp.encoding='gbk'
print(resp.text)#先打印页面源码
我们发现字符不是中文,是编码问题,所以将编码改成gbk,即去掉上段代码注释
用BeautifulSoup分析网页源代码,.find_all是匹配所有节点
page = BeautifulSoup(resp.text,"html.parser")
biao = page.find("div",class_="list").find_all("img")
下图是页面节点已找出
用for循环找出所有网址
for i in biao:
wangzhi = i.get('src')
print(wangzhi)
下面是找出的所有网址
接下来是下载这些url
wang_resp = requests.get(wangzhi)
wang_name = wangzhi.split("/")[-1] #给图片重命名
with open("pic/"+wang_name,mode="wb")as f: #pic是文件夹名,可以换成路径
f.write(wang_resp.content)#图片写入文件,content是写入字节,自动转成图片
print("{} {}".format(wang_name,"下载完成"))
time.sleep(1)#设置个时间等待,防止网址禁止你访问
以下是所有代码
import requests
from bs4 import BeautifulSoup
import time
"""
urll = ["http://www.netbian.com/weimei/index.htm","http://www.netbian.com/weimei/index_2.htm","http://www.netbian.com/weimei/index_3.htm",
"http://www.netbian.com/weimei/index_4.htm","http://www.netbian.com/weimei/index_5.htm"]
for url in urll:
resp = requests.get(url)
resp.encoding='gbk'
pag = BeautifulSoup(resp.text,"html.parser")
biao = pag.find("div",class_="list").find_all("img")
for i in biao:
wangzhi = i.get('src')
用for循环下载网页下一页壁纸,替换22到33行就可以
"""
url = "http://www.netbian.com/weimei/index.htm"
resp = requests.get(url)
resp.encoding='gbk'
#print(resp.text)
page = BeautifulSoup(resp.text,"html.parser")
biao = page.find("div",class_="list").find_all("img")
for i in biao:
wangzhi = i.get('src')
#print(wangzhi)
wang_resp = requests.get(wangzhi)
wang_name = wangzhi.split("/")[-1] #给图片重命名
with open("pic/"+wang_name,mode="wb")as f: #pic是文件夹名,可以换成路径
f.write(wang_resp.content)#图片写入文件,content是写入字节,自动转成图片
print("{} {}".format(wang_name,"下载完成"))
time.sleep(1)#设置个时间,防止网址禁止你访问
print("已全部下载完成")
我也是初学者,大家一起加油。