我正在尝试从多个气象站收集每月的气象站数据,但无法选择数据间隔框来为每个气象站选择适当的“每月”选项。
使用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")
但是,它只更改了第一个select元素。
我还在其他站点的div和select元素上尝试了.click()
方法,但两者都返回错误"element not interactable“。
我也尝试过使用动作链。
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,但我怀疑这可能是与适当的选项元素交互的关键。有人知道如何从多个下拉菜单中选择一个选项吗?
发布于 2019-08-10 01:21:31
尝试这种方法。您应该能够遍历每个站点并选择所需的间隔来收集数据。
#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)
发布于 2019-08-10 00:39:55
我只使用.click()方法就可以在没有javascript的情况下选择monthly。
然而,我使用了一个不同的选择器: //divtext()='KEJIMKUJIK 1'/following-sibling::div/following-sibling::div//labeltext()='Data Interval'/following-sibling::select
当然,你可以用任何站点替换“KEJIMKUJIK 1”文本。
如果它起作用了,请告诉我。否则,我可以添加我的代码。
https://stackoverflow.com/questions/57433734
复制相似问题