python - 使用 python 和 selenium 使用图像的“src”属性下载图像
问题描述
我是 Python 和 Selenium 的新手。我的目标是从 Google 图片搜索结果页面下载图片并将其作为文件保存在本地目录中,但我最初无法下载图片。
我知道还有其他选项(使用请求通过 url 检索图像等),但我想知道是否可以使用图像的“src”属性,例如“data:image/jpeg; base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wCEAAkGBxM..."
我的代码如下(为简洁起见,我删除了所有导入等。):
# This creates the folder to store the image in
if not os.path.exists(save_folder):
os.mkdir(save_folder)
driver = webdriver.Chrome(PATH)
# Goes to the given web page
driver.get("https://www.google.com/imghp?hl=en&ogbl")
# "q" is the name of the google search field input
search_bar = driver.find_element_by_name("q")
# Input the search term(s)
search_bar.send_keys("Ben Folds Songs for Silverman Album Cover")
# Returns the results (basically clicks "search")
search_bar.send_keys(Keys.RETURN)
# Wait 10 seconds for the images to load on the page before moving on to the next part of the script
try:
# Returns a list
search_results = WebDriverWait(driver, 10).until(
EC.presence_of_element_located((By.ID, "islrg"))
)
# print(search_results.text)
# Gets all of the images on the page (it should be a list)
images = search_results.find_elements_by_tag_name("img")
# I just want the first result
image = images[0].get_attribute('src')
### Need help here ###
except:
print("Error")
driver.quit()
# Closes the browser
driver.quit()
我努力了:
urllib.request.urlretrieve(image, "00001.jpg")
和
urllib3.request.urlretrieve(image, f"{save_folder}/captcha.png")
但我总是使用这些方法点击“例外”块。在阅读了一篇有前途的帖子后,我还尝试了:
bufferedImage = imageio.read(image)
outputFile = f"{save_folder}/image.png"
imageio.write(bufferedImage, "png", outputFile)
结果相似,尽管我相信后一个示例在帖子中使用了 Java,并且我在将其转换为 Python 时可能出错了。
我确定这很明显,但是我做错了什么?感谢您的任何帮助。
解决方案
在这种情况下,您正在处理的 URL 是一个数据 URL,它是以 base64 编码的图像本身的数据。
从 Python 3.4+ 开始,您可以读取此数据并将其解码为字节urllib.request.urlopen
:
import urllib
data_url = "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wCEAAkGBxM..."
with urllib.request.urlopen(data_url) as response:
data = response.read()
with open("some_image.jpg", mode="wb") as f:
f.write(data)
或者,您可以自己解码数据 url 的 base64 编码部分base64
:
import base64
data_url = "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wCEAAkGBxM..."
base64_image_data = data_url.split(",")[1]
data = base64.b64decode(base64_image_data)
with open("some_image.jpg", mode="wb") as f:
f.write(data)
推荐阅读
- java - 我不知道如何完成此代码以显示收藏夹列表
- opencv - 如何通过命令行(Ubuntu)编译 OpenCV 程序?
- java - 如何在 Netbeans 中编写 JFrame 而不是拖放?
- javascript - 如何将多个属性键作为参数传递给使用括号表示法的函数?
- angular - 如何使用 adal-angular5 在 angular 5 中刷新令牌
- c - 更改后自动重新编译C程序?
- python - 更改 base64 字符串并将其保存为图像
- c# - 在streamreader c#中按过滤器搜索
- ios - 隐藏视图后如何更新布局
- android - 不适用于 Oreo 8.1 的小部件案例 - 收到消息:W/BroadcastQueue:不允许后台执行:接收 Intent