PYTHON笔记一:通过PYTHON从网页批量下载图片

本文介绍通过PYTHON从网页批量下载图片的代码,示例网站:wall.alphacoders.com

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
url = "https://wall.alphacoders.com/"
import requests
headers = {"user-agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.45 Safari/537.36"} #伪装成浏览器
resp = requests.get(url,headers=headers)
print(resp.status_code) #CODE若为200,则可以正常爬取数据
resp.encoding = "utf-8" #根据网页本身的编码进行更改
#print(resp.text)

from bs4 import BeautifulSoup
soup = BeautifulSoup(resp.text,"html.parser")
tags = soup("img") #爬取"img"标签
import os

for tag in tags:
if tag.get("src") and tag.get('width') == "600": #"src"属性存在,且"width"属性值为600
img_src = tag.get("src")
img_width = tag.get("width")
filename = os.path.basename(img_src)
with open(f"picture/{filename}","wb") as fout:
fout.write(requests.get(img_src).content)
print(img_src,filename,img_width)

print("download is done, ok")
  • 本文作者:括囊无誉
  • 本文链接: Python/python-1-download-img/
  • 版权声明: 本博客所有文章均为原创作品,转载请注明出处!
------ 本文结束 ------
坚持原创文章分享,您的支持将鼓励我继续创作!