如何从多个下拉菜单中选择选项Selenium

时间:2019-08-09 16:05:51

标签: python selenium parsing webdriver

我正在尝试从多个气象站收集每月气象站数据,但是无法选择“数据间隔”框来为每个气象站选择适当的“每月”选项。

使用Selenium的Select功能,我可以使用以下代码更改第一个气象站的选项:

driver = webdriver.Chrome('path_to_driver')
driver.implicitly_wait(5)

driver.get("http://climate.weather.gc.ca/historical_data/search_historic_data_stations_e.html?searchType=stnProx&timeframe=1&txtRadius=25&selCity=&optProxType=park&selPark=44%7C23%7C65%7C17%7CKejimkujik+National+Park&txtCentralLatDeg=&txtCentralLatMin=&txtCentralLatSec=&txtCentralLongDeg=&txtCentralLongMin=&txtCentralLongSec=&optLimit=yearRange&StartYear=1840&EndYear=2019&Year=2019&Month=8&Day=3&selRowPerPage=10")

select = Select(driver.find_element_by_tag_name('select'))

select.select_by_visible_text("Monthly")

但是它只更改第一个选择元素。

我还在div和其他站点的select元素上都尝试了.click()方法,但是都返回了“元素不可交互”的错误。

我也尝试过使用动作链

driver = webdriver.Chrome('path_to_driver')
driver.implicitly_wait(5)

driver.get('http://climate.weather.gc.ca/historical_data/search_historic_data_stations_e.html?searchType=stnProx&timeframe=1&txtRadius=25&selCity=&optProxType=park&selPark=44%7C23%7C65%7C17%7CKejimkujik+National+Park&txtCentralLatDeg=&txtCentralLatMin=&txtCentralLatSec=&txtCentralLongDeg=&txtCentralLongMin=&txtCentralLongSec=&optLimit=yearRange&StartYear=1840&EndYear=2019&Year=2019&Month=8&Day=3&selRowPerPage=10')

# path to div element
kejipark_div_menu = driver.find_element_by_css_selector("#timeframe1-sm")
# path to select element
kejipark_select_submenu = driver.find_element_by_css_selector("#timeframe1-sm > option:nth-child(2)")


try:
    actions = ActionChains(driver)
    actions.move_to_element(kejipark_div_menu)
    actions.click(kejipark_hidden_submenu)
    actions.perform()

finally:
    driver.quit()

返回错误:“ javascript错误:无法读取未定义的属性'left'”

我不熟悉javascript,但我怀疑这可能是与适当的option元素进行交互的关键。有谁知道如何从多个下拉菜单中选择一个选项?

2 个答案:

答案 0 :(得分:0)

我仅使用.click()方法就可以每月选择一次,而无需使用javascript。

但是,我使用了一个不同的选择器: // div [text()='KEJIMKUJIK 1'] / following-sibling :: div / following-sibling :: div // label [text()='Data Interval'] / following-sibling :: select

您当然可以将“ KEJIMKUJIK 1”文本替换为任何电台。

让我知道它是否有效。否则,我可以添加我的代码。

答案 1 :(得分:0)

尝试这种方法。您应该能够遍历每个站点并选择所需的间隔来收集数据。

#Find Each Station and loop through

Stations = driver.find_elements_by_xpath("//*[@class='row']/form/div[@class='col-lg-3 col-md-3 col-sm-3 col-xs-3']")
print("Number of Stations", len(Stations))
time.sleep(3)

for Station in Stations:
    print("The station name is: ", Station.text)
    # Find Data Interval and select Monthly
    Interval = driver.find_element_by_xpath("//div[text()='"+Station.text+"']/following-sibling::div//label[contains(text(),'Data Interval')]/following::select[@name='timeframe'][1]")
    Interval.click()
    Interval.send_keys("Monthly")
    time.sleep(2)
相关问题