Python爬虫案例-获取图片
# 1.拿到主页的源代码,然后提取到子页面的链接地址,href
# 2.通过href拿到子页面的内容,从子页面中找到图片的下载地址
import requests
from bs4 import BeautifulSoup
import time
url="https://umei.cc/bizhitupian/weimeibizhi/"
resp=requests.get(url)
resp.encoding=resp.apparent_encoding
#把源代码交给BeautifulSoup
main_page=BeautifulSoup(resp.text,"html.parser")
alist=main_page.find("div",class_="TypeList").find_all("a")
for a in alist:
href=(a.get("href"))
#拿到源代码
child_page_resp=requests.get("https://umei.cc"+href)
child_page_resp.encoding=child_page_resp.apparent_encoding
#源代码交给BS
child_page=BeautifulSoup(child_page_resp.text,"html.parser")
#找下载路径
p=child_page.find("p",align="center")
img=p.find("img")
src=img.get("src")
#下载图片
img_resp=requests.get(src)
#这里拿到的是字节img_resp.content
#拿到url最后的一个部分(最后的”/“后面的内容)
img_name=src.split("/")[-1]
with open(img_name,"wb") as f:
# 图片内容的二进制写入文件
f.write(img_resp.content)
print("over",img_name)
time.sleep(1)
print("all over")
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
推荐阅读