python 爬虫 -----Bs4 爬取并且下载图片

# 1.拿到主页面主代码,拿到子页面连接地址,href
# 2.通过href拿到子页面内容,从子页面中找到图片的下载地址 img -> src
# 3. 下载图片
import requests
from bs4 import BeautifulSoup
import time
import urllib3

urllib3.disable_warnings() # 去除警告

url = "https://www.umei.cc/bizhitupian/weimeibizhi/"
domain = "https://www.umei.cc/"

resp = requests.get(url, verify=False)
resp.encoding = 'utf-8' # 调整字符编码
# print(resp.text)

main_page = BeautifulSoup(resp.text, "html.parser") # 指定html解析器
alist = main_page.find("div", class_="item_list infinite_scroll").find_all("a") # 查找数据
# print(alist)

for a in alist:
    # print(a.get("href")) # 直接通过get就可以拿到属性的值
    href = domain + a.get('href').strip("/") # 拼接连接
    # print(href)
    # 拿到子页面源代码
    child_resp = requests.get(href, verify=False) # 拿到源代码 去掉了安全验证
    child_resp.encoding = 'uft-8' # 调整字符编码
    # 提取下载路径
    child_page = BeautifulSoup(child_resp.text, "html.parser") # 指定html解析器
    p = child_page.find("div", class_="big-pic") # 查找数据
    img = p.find("img")# 得到连接img
    # print(img.get("src"))
    src = img.get("src")# 得到属性值src

    # 下载图片
    img_resp = requests.get(src, verify=False) # 拿到连接 去掉了安全验证
    # img_resp.content #拿到字节
    img_name = src.split("/")[-1] # 拿到url中最后一个/以后的内容 命名
    with open("img/"+img_name, mode="wb") as f: # 打开文件
        f.write(img_resp.content) # 写入到文件

    print("over!!", img_name) # 结束语句
    time.sleep(1) # 停止语句

print("all over!!") # 爬取完毕语句
resp.close() # 关闭请求

 

posted @ 2022-10-28 19:30  slowlydance2me  阅读(105)  评论(0编辑  收藏  举报