python程序批量下载一个php页面中的所有图片请帮我写一段代码
以下是一个Python程序,它可以批量下载一个PHP页面中的所有图片:
import os
import requests
from bs4 import BeautifulSoup
# 要下载的PHP页面的URL
url = "http://example.com/page.php"
# 获取页面内容
response = requests.get(url)
soup = BeautifulSoup(response.content, "html.parser")
# 创建一个目录来保存所有的图片
if not os.path.exists("images"):
os.makedirs("images")
# 找到所有的图片标签,并下载它们
for img in soup.find_all("img"):
img_url = img["src"]
if not img_url.startswith("http"):
img_url = url + img_url
img_name = img_url.split("/")[-1]
img_path = os.path.join("images", img_name)
with open(img_path, "wb") as f:
f.write(requests.get(img_url).content)
print("已下载:", img_path)
该程序使用了Requests和BeautifulSoup库来获取和解析PHP页面的内容,然后找到所有的图片标签,并使用Requests库将它们下载到一个名为"images"的目录中。程序还处理了一些特殊情况,例如图片的URL可能是相对的,需要根据PHP页面的URL拼接成完整的URL。
原文地址: https://www.cveoy.top/t/topic/b0zL 著作权归作者所有。请勿转载和采集!