首页 > 解决方案 > 仅在渲染时获取数据url时访问数据图像url

问题描述

我想在页面呈现后使用相应的数据 URL自动获取保存为浏览器数据的图像。

例如:

  1. 你可以去网页:https ://en.wikipedia.org/wiki/Truck
  2. 使用 Firefox 的 WebInspector 选择右侧的第一个缩略图。
  3. 现在在 Inspector 选项卡上,右键单击 img 标签,转到 Copy 并按“Image Data-URL”
  4. 打开一个新选项卡,粘贴并输入以查看来自数据 URL 的图像。

请注意,数据 URL 在页面源上不可用。在我要抓取的网站上,图像在通过 php 脚本后呈现。如果尝试使用 src 标签属性直接访问图像,服务器将返回 404 响应。

我相信应该可以列出网站呈现的图像的数据 URL 并下载它们,但是我无法找到一种方法来做到这一点。

我通常使用 selenium webdriver 和用 python 编码的 Firefox 进行抓取,但任何解决方案都会受到欢迎。

标签: seleniumselenium-webdriverweb-scrapingphantomjs

解决方案


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 张图片。这是第一张图片:

在此处输入图像描述

希望这会有所帮助!


推荐阅读