我试图使用selenium帮助从使用javascript加载信息的网站检索数据。
你可以在这里看到链接:Animal population
页面显示了一些可选择的字段,为了我的目的,我试图检索2011年英国蜜蜂数量的数据。
提交可选字段后,页面将加载包含相应数据的表。我只想知道全国的人口和密度。
到目前为止,我的代码只选择了年份、国家和物种字段,并且在返回表之后,它定位了“整个国家”字段(可以自由地告诉我如何改进我现有的代码)。
我无法检索全国的人口和密度字段,我尝试了xpath和'following sibling',但它显示了查找元素的异常。
我也不想依赖行/单元格的位置,因为我还将尝试在接下来的几年中获取此信息,并且表字段将更改位置。

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

driver = webdriver.Firefox()
driver.get('https://www.oie.int/wahis_2/public/wahid.php/Countryinformation/Animalpopulation')



select = Select(driver.find_element_by_id('country6'))
select.select_by_value('GBR')
select = Select(driver.find_element_by_id('year'))
select.select_by_value('2011')

try:
    element = WebDriverWait(driver, 40).until(EC.presence_of_element_located((By.CLASS_NAME, "TableContent ")))
    print element
    select = Select(driver.find_element_by_id('selected_species'))
    select.select_by_value('1')
except:
    print "Not found"

country_td = driver.find_element(By.XPATH, '//td/b[text()="The Whole Country"]')

#population_td = driver.find_element(By.XPATH, '//td/b[text()="The Whole Country"]/following-sibling::text()')
print country_td.text

谢谢你的帮助。

最佳答案

要使用following-sibling获取数据,您需要向上一级

population = driver.find_element(By.XPATH, ('//td[b[text()="The Whole Country"]]/following-sibling::td[1]')
density = driver.find_element(By.XPATH, ('//td[b[text()="The Whole Country"]]/following-sibling::td[2]')

或使用country_td
population = country_td.find_element(By.XPATH, ('/../following-sibling::td[1]')
density = country_td.find_element(By.XPATH, ('/../following-sibling::td[2]')

07-24 09:38
查看更多