python - 使用 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)
解决方案
您可以选择<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)
推荐阅读
- pdftk - pdftk无法打开文件
- r - 无法提取我在 Panoply 中看到的 R 中的 netcdf 变量
- python - IndexError:标量变量的索引无效,我已尝试使用其他简单函数使用相同的公式,但它不起作用
- c# - C# Azure DevOps Git:无法推送新目录
- ibm-cloud - 如何在 IbmCloud 中部署应用程序?
- git - Azure Devops - 从另一个组织导入 git repo 链接到另一个项目中的工作项
- javascript - 在 Redux 的反应中更新数组中对象中的值
- r - 如何使用ggplot2中的geom_bar从小到大绘制负数
- angular - Angular - 主机监听器/UnloadNotification - 即使确认被拒绝,历史仍然会改变
- node.js - 为什么用户 multer 后我看不到图像?