【问题标题】:Selinum Driver wait for SVG to be completely rendredSelenium Driver 等待 SVG 完全渲染
【发布时间】:2019-03-06 08:39:05
【问题描述】:

我正在使用 Selenium 和 Chrome 驱动程序来废弃包含 SVG 的页面。 我需要一种方法让 Selenium 等到 svg 完全加载,否则我会在报废时得到一些不完整的图表。

目前脚本在开始抓取之前等待 10 秒,但这对于抓取 20000 页来说已经很多了。

 def page_loaded(driver):
        path = "//*[local-name() = 'svg']"
        time.sleep(10)
        return driver.find_element_by_xpath(path)

 wait = WebDriverWait(self.driver, 10)
 wait.until(page_loaded) 

在开始报废之前是否有任何有效的方法来检查 SVG 是否已加载?

【问题讨论】:

  • 相信你在找from selenium.webdriver.support.ui import WebDriverWait
  • 我已经在使用上面的函数作为停止等待的条件。代码更新

标签: python svg web-scraping selenium-chromedriver


【解决方案1】:

Selenium 文档中的一个示例:

from selenium.webdriver.support import expected_conditions as EC

wait = WebDriverWait(driver, 10)
element = wait.until(EC.element_to_be_clickable((By.ID, 'someid')))

所以在你的情况下应该是:

from selenium.webdriver.support import expected_conditions as EC

wait = WebDriverWait(self.driver, 10)
element = wait.until(EC.presence_of_element_located((By.XPATH, path)))

这里10 中的WebDriverWait(driver, 10) 是等待的最大秒数。即它一直等到 10 点或条件,以先到者为准。

自动化网络浏览器时经常使用的一些常见条件:

  • title_is title_contains
  • presence_of_element_located
  • visibility_of_element_located visibility_of
  • presence_of_all_elements_located
  • text_to_be_present_in_element
  • text_to_be_present_in_element_value 等等。 More available here.

Also here's the documentation for expected conditions support.

解决此问题的另一种方法是编写 on 方法,例如:

def find_svg(driver):
    element = driver.find_element_by_xpath(path)
    if element:
        return element
    else:
        return False

然后调用 Webdriver 等待如下:

element = WebDriverWait(driver, max_secs).until(find_svg)

【讨论】:

  • 我的代码和你写的完全一样。它等待 svg 出现,但问题是我想等待它被浏览器渲染。您编写的代码并没有这样做,它只是检查一个元素是否存在,而不是它是否完全渲染。当我说 10 秒时,我的意思是 time.sleep(10)
  • 您的具体用例是什么?也许您应该添加更多信息,例如 html_source。这是一个建议。如果 svg 元素有一定的高度和宽度,你可以检查一下吗?还是按大小?
  • 无论如何这都是一个有趣的问题。这是一个可能对您有所帮助的链接。 sqa.stackexchange.com/questions/13625/…
  • 问题是 svg 内容而不是它自己的 svg 标签。如果您不等待它的内容被渲染(因页面而异),您在报废时不会得到正确的内容。
  • 您是否要下载 svg 内容?如果是这样,则抓取src 属性并从该链接下载。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-12-29
  • 1970-01-01
  • 1970-01-01
  • 2020-04-07
  • 1970-01-01
相关资源
最近更新 更多