学了一段时间python,最近学习了一些python爬虫,今天写了一个爬取优美图库的的一段代码,下面给大家分享一下。
先看一下爬取的结果:
这段代码使用了下面的一些包,我们需要提前进行安装,在终端使用pip就可安装。
import requestsfrom bs4 import BeautifulSoupimport time
我在代码的最外层加入了一个for循环,可以进行爬取多个页面
for page in range(2,5,1):url=f"/bizhitupian/meinvbizhi/index_{page}.htm"
在代码的最后一定要记得关闭请求,并且在每个请求中间使用sleep休息一秒,防止多次访问未关闭或者访问速度过快,可能会导致网站禁止你的ip访问。
child_resp.close()time.sleep(1)resp.close()
下面把整个的代码放上
# 时间:/10/12 16:32import requestsfrom bs4 import BeautifulSoupimport timefor page in range(2,5,1): #这里可以更改需要图片的数量url=f"/bizhitupian/meinvbizhi/index_{page}.htm"resp = requests.get(url)resp.encoding = 'utf=8' #处理乱码# print(resp.text)main_page = BeautifulSoup(resp.text, "html.parser")alist = main_page.find("div", class_="TypeList").find_all("a")# print(alist)for a in alist:href = "" + a.get('href')# print(href)# 拿到子页面的源代码child_resp = requests.get(href)child_resp.encoding = "utf-8"child_text = child_resp.text# 从子页面中拿到图片的下载路径child_page = BeautifulSoup(child_text, 'html.parser')p = child_page.find("p", align="center")img = p.find("img")# print(img.get("src"))src = img.get("src")# 下载图片img_resp = requests.get(src)img_name = src.split("/")[-1]with open("img2/" + img_name, mode="wb") as f:f.write(img_resp.content) # 图片内容写入文件print(img_name, "下载完成")img_resp.close()child_resp.close()time.sleep(1)resp.close()print("下载结束")
注意::在运行之前要新建一个文件夹,命名为img
如果觉得《python爬取优美图库》对你有帮助,请点赞、收藏,并留下你的观点哦!