import os
import requests
from bs4 import BeautifulSoup
import urllib.request
def look_img(soup,i):
# 抓取图片地址
# 抓取img标签
img_src = soup.findAll("img")
n = 1
url_img = [] # 保存需要爬取图片的地址
for img in img_src:
n = n + 1
img = img.get('src') # 抓取src
if (n == 5):
url_img = img
print(url_img)
# 保存图片
root = "C://Users//123//Desktop//images//" # 保存的根目录
path = root + str(i) + ".jpg" # 保存的地址
try:
if not os.path.exists(root): # 判断根目录是否存在
os.mkdir(root)
if not os.path.exists(path): # 如果文件不存在就爬取并保存
r = requests.get(url_img)
with open(path, 'wb') as f: # 'wb'以二进制格式打开一个文件只用于写入。如果该文件已存在则将其覆盖。如果该文件不存在,创建新文件。
f.write(r.content) # content返回二进制数据,所以使用'wb'
f.close()
print("文件保存成功")
else:
print("文件已存在")
except:
print("爬取失败")
def main():
url = 'http://www.cd3000y.com/html/movablerelics/A-01-0000001-1255258500.html'
r = requests.get(url)
r.encoding = r.apparent_encoding
demo = r.text
soup = BeautifulSoup(demo, "html.parser")
look_img(soup,1)
main()
python爬取网站图片url并保存在本地文件夹
最新推荐文章于 2023-09-25 15:56:31 发布