python爬图片【Python爬图片:代码示例】

xl1407

温馨提示:这篇文章已超过241天没有更新,请注意相关的内容是否还可用!

python爬图片【Python爬图片:代码示例】

Python爬取图片可以使用第三方库requests和BeautifulSoup来实现。我们需要使用requests库发送HTTP请求获取网页的HTML内容,然后使用BeautifulSoup库解析HTML内容,提取出图片的URL地址。使用requests库再次发送HTTP请求,将图片保存到本地。

以下是一个示例代码,演示如何使用Python爬取图片:

import requests

from bs4 import BeautifulSoup

def download_image(url, filename):

response = requests.get(url)

with open(filename, 'wb') as f:

f.write(response.content)

def crawl_images(url):

response = requests.get(url)

soup = BeautifulSoup(response.text, 'html.parser')

img_tags = soup.find_all('img')

for img_tag in img_tags:

img_url = img_tag['src']

if img_url.startswith('http'):

filename = img_url.split('/')[-1]

download_image(img_url, filename)

url = 'https://www.example.com' # 替换为你要爬取图片的网页URL

crawl_images(url)

在上面的代码中,我们定义了两个函数。`download_image`函数用于下载图片,它接受图片的URL和保存的文件名作为参数。`crawl_images`函数用于爬取图片,它接受网页的URL作为参数。

我们使用`requests.get`方法发送HTTP请求,获取网页的HTML内容。然后,我们使用BeautifulSoup库将HTML内容解析成一个BeautifulSoup对象。接着,我们使用`find_all`方法找到所有的`img`标签,然后遍历每个`img`标签,提取出图片的URL地址。如果图片的URL以`http`开头,说明是绝对路径,我们使用`split`方法获取文件名,并调用`download_image`函数下载图片。

你可以将`url`变量替换为你要爬取图片的网页URL,运行代码后,图片将会保存在当前目录下。

文章版权声明:除非注明,否则均为莫宇前端原创文章,转载或复制请以超链接形式并注明出处。

取消
微信二维码
微信二维码
支付宝二维码