栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

python爬取优美图库

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

python爬取优美图库

学了一段时间python,最近学习了一些python爬虫,今天写了一个爬取优美图库的的一段代码,下面给大家分享一下。

先看一下爬取的结果:

这段代码使用了下面的一些包,我们需要提前进行安装,在终端使用pip就可安装。

import requests
from bs4 import BeautifulSoup
import time

我在代码的最外层加入了一个for循环,可以进行爬取多个页面

for page in range(2,5,1):
    url=f"https://www.umei.cc/bizhitupian/meinvbizhi/index_{page}.htm"

在代码的最后一定要记得关闭请求,并且在每个请求中间使用sleep休息一秒,防止多次访问未关闭或者访问速度过快,可能会导致网站禁止你的ip访问。

		child_resp.close()
        time.sleep(1)
    resp.close()

下面把整个的代码放上

# 时间:2021/10/12 16:32

import requests
from bs4 import BeautifulSoup
import time
for page in range(2,5,1):  #这里可以更改需要图片的数量
    url=f"https://www.umei.cc/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 = "https://www.umei.cc" + 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

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/324421.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号