如何通过Selenium和Python按与该URL相同的文本单击“导出”按钮?

时间:2018-09-04 09:41:03

标签: selenium selenium-webdriver webdriver webdriverwait

我遇到了麻烦,希望您能帮上忙。我不是Python天才,因此对语言深表歉意。我需要点击此网站https://www.fec.gov/data/filings/?data_type=processed&committee_id=C00097485上的按钮(导出)。该按钮应驱动到页面底部,该页面底部显示指向Excel文件的链接。现在,我使用了以下代码:

text="//button[@type='button' and contains(.,'Export')]"
driver = webdriver.Firefox()
driver.get("https://www.fec.gov/data/filings/data_type=processed&committee_id=C00142711")
time.sleep(5)
button=driver.find_element_by_xpath(text)
button.click

脚本运行正常,没有错误消息。该网站出现,但是“单击”没有发生。 我还尝试了:1)“等待驱动程序,直到元素可单击”,2)ActionChain移动光标,3)用sendKeys代替click。 没有iframe。我也在Chrome上尝试过。我正在Windows 10上使用PC。

我在做什么错???考虑到与其他网站一起,单击功能可以很好地工作!

2 个答案:

答案 0 :(得分:0)

点击是一种方法,因此应为button.click()。您缺少父母。

此外,最好使用WebDriverWait而不是.sleep(),例如button = WebDriverWait(driver, 20).until( EC.element_to_be_clickable((By.XPATH, text)));

答案 1 :(得分:0)

根据 url ,带有文本 Export 的按钮是启用了JavaScript的元素,因此您需要诱导_WebDriverWait_来使元素成为clickable ,您可以使用以下解决方案:

  • 代码块:

    from selenium import webdriver
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.support import expected_conditions as EC
    
    driver = webdriver.Firefox()
    driver.get("https://www.fec.gov/data/filings/?data_type=processed&committee_id=C00097485")
    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "button.js-export.button.button--cta.button--export"))).click()
    
  • 浏览器快照:

fec_gov