本文介绍了如何从 BeautifulSoup 下载图片?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

图片 http://i.imgur.com/OigSBjF.png

导入请求从 bs4 导入 BeautifulSoup

import requests from bs4 import BeautifulSoup

r = requests.get("xxxxxxxxx")
soup = BeautifulSoup(r.content)

for link in links:
    if "http" in link.get('src'):
       print link.get('src')

我得到了打印的 URL,但不知道如何使用它.

I get the printed URL but don't know how to work with it.

推荐答案

您需要下载并写入磁盘:

You need to download and write to disk:

import requests
from os.path  import basename

r = requests.get("xxx")
soup = BeautifulSoup(r.content)

for link in links:
    if "http" in link.get('src'):
        lnk = link.get('src')
        with open(basename(lnk), "wb") as f:
            f.write(requests.get(lnk).content)

您还可以使用 select 来过滤您的标签以仅获取带有 http 链接的标签:

You can also use a select to filter your tags to only get the ones with http links:

for link in soup.select("img[src^=http]"):
        lnk = link["src"]
        with open(basename(lnk)," wb") as f:
            f.write(requests.get(lnk).content)

这篇关于如何从 BeautifulSoup 下载图片?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-05 09:46