爬虫之爬取图片(运用了bs4和正则查取)

我们以美图优优这个网站进行爬取(网址)

https://m.umei.cc/bizhitupian/shoujibizhi/

首先我们分析网页
在这里插入图片描述
然后我们点开高清图片链接,跳转到一个新的页面,然后对新的页面进行网页分析
在这里插入图片描述
然后我们可以开始编写代码了:

# @Time:2021/11/2114:27
# @Author:中意灬
# @File:美图优优.py
# @ps:tutu qqnum:2117472285

#步骤:
    #1.通过主页面获取子链接
    #2.通过子链接获取高清图片连接
    #3.通过子链接得到图片的字节流
    #4.保存图片
import csv
import re
import time
import requests
from bs4 import BeautifulSoup
patter=re.compile(r'<h1>(?P<name>.*?)</h1>')#为了后面获取图片名字指定的规则
header={
    
    
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.81 Safari/537.36"
}
url="https://m.umei.cc/bizhitupian/shoujibizhi/"
resp1=requests.get(url)
resp1.encoding='utf-8'
#把网页源代码交给BeatifulSoup进行处理,产生bs对象
html1=BeautifulSoup(resp1.text,'html.parser')#指定用html解析
a=html1.find('div',class_="pic-list pic-list-2 pic-list-shadow").find_all("a")#拿到a标签内的内容
for i in a:
    href=i.get('href')#获取到的子链接
    try:
        resp2=requests.get("https://m.umei.cc"+href)
        resp2.encoding='utf-8'
        name = patter.findall(resp2.text)#获取到图片的名字
        html2=BeautifulSoup(resp2.text,"html.parser")
        img=html2.find("div",class_="arc-bodys").find('img')
        src=img.get("src")#获取到的高清图片链接
        img_down=requests.get(src)#下载图片
        #img_down.content是获取图片的字节流
        with open("img/"+name[0]+".jpg",mode="wb") as f:#保存在img这个文件夹里,以图片名字命名,保存为jpg形式
         f.write(img_down.content)#将高清图片的内容以字节流的方式保存
        print(name[0]+"over")
        time.sleep(0.1)
    except Exception as e:
        print(e)
print("over!")


运行结果(截取了一部分):
在这里插入图片描述
在这里插入图片描述
建议:大家可以自己多加循环,这样就可以将整个将整个网站的图片都慢慢的爬取出来了

猜你喜欢

转载自blog.csdn.net/qq_55977554/article/details/121454968