2

我正在努力使用 Selenium 下载 CSV 文件几天。请指教,不胜感激!!

我使用 Selenium Webdriver Language Bindings (Python) 2.4 + HTMLUnit 浏览器。

代码:

browser.find_element_by_id("generate_csv").click()
csv_file = browser.page_source

在那个网页中,如果我使用 Firefox,点击“generate_csv”按钮后,它会生成一个 CSV 文件,通常会下载它。由于我使用的是 HTMLUnit,所以很难实现下载文件,所以我使用page_source属性来获取 CSV 内容。

有时,它是成功的!但有时它会抛出错误:

org.openqa.selenium.NoSuchElementException: Returned node was not an HTML element

有人可以帮我分析为什么会这样吗?我很困惑,运行脚本就像掷骰子。

谢谢你。

更新:(回溯的一部分)

14:29:15.913 INFO - Executing: [find element: By.selector: .controlbuttons > a > img[alt='CSV']])
14:29:16.404 WARN - Exception thrown
org.openqa.selenium.NoSuchElementException: Returned node was not an HTML element
For documentation on this error, please visit: ...
Driver info: driver.version: EventFiringWebDriver
    at org.openqa.selenium.htmlunit.HtmlUnitDriver.findElementByCssSelector(HtmlUnitDriver.java:952)
    at org.openqa.selenium.By$ByCssSelector.findElement(By.java:426)
    at org.openqa.selenium.htmlunit.HtmlUnitDriver$5.call(HtmlUnitDriver.java:1565)
    at org.openqa.selenium.htmlunit.HtmlUnitDriver$5.call(HtmlUnitDriver.java:1)
    at org.openqa.selenium.htmlunit.HtmlUnitDriver.implicitlyWaitFor(HtmlUnitDriver.java:1241)
    at org.openqa.selenium.htmlunit.HtmlUnitDriver.findElement(HtmlUnitDriver.java:1562)
    at org.openqa.selenium.htmlunit.HtmlUnitDriver.findElement(HtmlUnitDriver.java:530)
    at sun.reflect.GeneratedMethodAccessor129.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at org.openqa.selenium.support.events.EventFiringWebDriver$2.invoke(EventFiringWebDriver.java:101)
    at com.sun.proxy.$Proxy14.findElement(Unknown Source)
    at org.openqa.selenium.support.events.EventFiringWebDriver.findElement(EventFiringWebDriver.java:184)
    at org.openqa.selenium.remote.server.handler.FindElement.call(FindElement.java:47)
    at org.openqa.selenium.remote.server.handler.FindElement.call(FindElement.java:1)
    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:303)
    at java.util.concurrent.FutureTask.run(FutureTask.java:138)
    at org.openqa.selenium.remote.server.DefaultSession$1.run(DefaultSession.java:169)
    at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:895)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:918)
    at java.lang.Thread.run(Thread.java:695)
14:29:16.405 WARN - Exception: Returned node was not an HTML element
4

1 回答 1

1

听起来您的 html 在您调用生成 csv 按钮之前没有完成加载。从 javascript 加载 html 时,这与 selenium 发生了一堆 - 至少对我来说。

不确定这是否是处理它的最佳方法,但我会使用递归方法单击直到你得到它......

import time
def generateCsv(browser):
    try:
        browser.find_element_by_id("generate_csv").click()
        csv_file = browser.page_source
    Except NoSuchElementException,e:
        time.sleep(3)
        generateCsv(browser)

希望有帮助

于 2014-07-03T03:12:51.510 回答