Selenium Webdriver 下载 CSV
我这几天一直在用Selenium下载CSV文件,遇到了一些困难。请给我一些建议,非常感谢!!
我使用的是Selenium Webdriver的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
1 个回答
1
听起来你的HTML在你点击生成CSV按钮之前还没有完全加载完。这种情况在使用Selenium加载JavaScript生成的HTML时经常发生,至少我遇到过很多次。
我不确定这是不是最好的解决办法,但我会用一种递归的方法来不断点击,直到成功为止……
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)
希望这能帮到你