失眠网,内容丰富有趣,生活中的好帮手!
失眠网 > python爬取优美图库

python爬取优美图库

时间:2023-11-04 10:29:57

相关推荐

python爬取优美图库

学了一段时间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爬取优美图库》对你有帮助,请点赞、收藏,并留下你的观点哦!

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。