0

我是 Python 3.X 的新手,需要编写一个脚本来自动化从 American Fact Finder 下载美国人口普查数据的过程。我正在使用 selenium webdriver,到目前为止我的代码是:

    driver = webdriver.Chrome(chromePath)

    #make driver navigate to American Fact Finder Download Center
    driver.get('https://factfinder.census.gov/faces/nav/jsf/pages/download_center.xhtml')

    #Make driver click 'Next' to go to Dataset page
    driver.find_element_by_xpath('''//*[@id="nextButton"]''').click()

    #this is where I need to locate the drop down and select American Community Survey'

在“数据集”页面上,我需要从下拉列表中选择“美国社区调查”,但无论我如何尝试找到运行脚本的下拉列表(xpath、id、值等)都会返回NoSuchElementException: no such element: Unable to locate element:

我需要帮助找到正确的元素并从下拉菜单中选择“美国社区调查”。

谢谢!

4

2 回答 2

0

我实际上能够自己解决它。

对于任何想知道的人来说,这个错误是因为 selenium 在页面完成加载之前试图找到元素。工作代码是:

from selenium import webdriver
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By

chromePath = r'chromedriver.exe'
driver = webdriver.Chrome(chromePath)

#make driver navigate to American Fact Finder Download Center

driver.get('https://factfinder.census.gov/faces/nav/jsf/pages/download_center.xhtml')
#Make driver click 'Next' to go to Dataset
driver.find_element_by_xpath('''//*[@id="nextButton"]''').click() #needs to be triple quoted
#make driver wait while page loads
timeout = 5
try:
    element_present = EC.presence_of_element_located((By.XPATH, '//*[@id="filterDimensionListId'))
    WebDriverWait(driver, timeout).until(element_present)
except TimeoutException:
    print ("Timed out waiting for page to load") 
#Choose ACS 5-year from drop down
driver.find_element_by_xpath('''//*[@id="filterDimensionListId"]/option[2]''').click()
于 2018-02-26T02:01:56.493 回答
0

你可以试试下面的代码来获取。

  select = Select(driver.find_element_by_id('filterDimensionListId'))      
    for index in range(len(select.options)):
        select = Select(driver.find_element_by_id('filterDimensionListId'))
        select.select_by_index(1)

// 您可以使用其他选择方法。

于 2018-02-26T07:06:27.743 回答