首页 > 解决方案 > 使用 BeautifulSoup 下载图像

问题描述

BeautifulSoup在我的 python 代码中使用从定期更改的网站下载图像。这一切都很好。

但是,在页面 ( https://apod.nasa.gov/apod/astropix.html ) 上有一张分辨率较低的图片(我的代码目前正在下载该图片),但是如果您单击该图片,它会将您带到更高分辨率的版本相同的图像。

有人可以建议我如何更改我的代码以下载更高分辨率的图像吗?:

from bs4 import BeautifulSoup as BSHTML
import requests
import subprocess
import urllib2
page = urllib2.urlopen('https://apod.nasa.gov/apod/astropix.html')
soup = BSHTML(page,features="html.parser")
images = soup.findAll('img')

url = 'https://apod.nasa.gov/apod/'+images[0]['src']
r = requests.get(url, allow_redirects=True)
with open('/home/me/Downloads/apod.jpg',"w") as f:
            f.write(r.content)

标签: pythonbeautifulsoup

解决方案


您可以选择<a>包含的标签,<img>然后"href"属性包含您的图像 URL:

import requests
from bs4 import BeautifulSoup as BSHTML

page = requests.get("https://apod.nasa.gov/apod/astropix.html")
soup = BSHTML(page.content, features="html.parser")

image_url = (
    "https://apod.nasa.gov/apod/" + soup.select_one("a:has(>img)")["href"]
)

r = requests.get(image_url, allow_redirects=True)
with open("/home/paul/Downloads/apod.jpg", "wb") as f:
    f.write(r.content)

推荐阅读