selenium - 仅在渲染时获取数据url时访问数据图像url
问题描述
我想在页面呈现后使用相应的数据 URL自动获取保存为浏览器数据的图像。
例如:
- 你可以去网页:https ://en.wikipedia.org/wiki/Truck
- 使用 Firefox 的 WebInspector 选择右侧的第一个缩略图。
- 现在在 Inspector 选项卡上,右键单击 img 标签,转到 Copy 并按“Image Data-URL”
- 打开一个新选项卡,粘贴并输入以查看来自数据 URL 的图像。
请注意,数据 URL 在页面源上不可用。在我要抓取的网站上,图像在通过 php 脚本后呈现。如果尝试使用 src 标签属性直接访问图像,服务器将返回 404 响应。
我相信应该可以列出网站呈现的图像的数据 URL 并下载它们,但是我无法找到一种方法来做到这一点。
我通常使用 selenium webdriver 和用 python 编码的 Firefox 进行抓取,但任何解决方案都会受到欢迎。
解决方案
BeautifulSoup
是用于此类问题陈述的最佳库。当你想从任何网站检索数据时,你可以盲目使用BeautifulSoup
,因为它比selenium
. BeautifulSoup
完成这个任务大约需要 10 秒,而selenium
完成同样的任务大约需要 15-20 秒,所以最好使用BeautifulSoup
. 这是你如何使用它BeautifulSoup
:
from bs4 import BeautifulSoup
import requests
import time
st = time.time()
src = requests.get('https://en.wikipedia.org/wiki/Truck').text
soup = BeautifulSoup(src,'html.parser')
divs = soup.find_all('div',class_ = "thumbinner")
count = 1
for x in divs:
url = x.a.img['srcset']
url = url.split('1.5x,')[-1]
url = url.split('2x')[0]
url = "https:" + url
url = url.replace(" ","")
path = f"D:\\Truck_Img_{count}.png"
response = requests.get(url)
file = open(path, "wb")
file.write(response.content)
file.close()
count+=1
print(f"Execution Time = {time.time()-st} seconds")
输出:
Execution Time = 9.65831208229065 seconds
29 张图片。这是第一张图片:
希望这会有所帮助!
推荐阅读
- python - 无法在 django admin 中保存嵌入式字段数据
- flutter - Flutter web 中似乎不支持字体粗细
- python - Pycharm 构建轮:“错误:命令错误,退出状态为 1”
- java - 为什么这个 While 循环不能正确执行
- git - 从合并的分支编辑提交消息
- php - 使用 PHP 使用 SQLite 的 Nginx 抛出错误
- java -
UnsupportedEncodingException 当我在带空格的变量后面写“”时发送电子邮件? - google-sheets - 在嵌入的 Google 工作表上悬停时显示注释
- postman - 如何将 newman 报告的结果发送给 Datadog?
- vim - Vim 弹出对话框无法调整大小