gpt4 book ai didi

python - 根据当前行的值获取下一行的值 Selenium

转载 作者:行者123 更新时间:2023-12-04 21:28:26 52 4
gpt4 key购买 nike

设置

我需要获取 this Wikipedia page 上所有 NUTS3 区域的人口数据。

我已经获得了每个 NUTS3 区域的所有 URL,并将让 Selenium 循环遍历它们以获取页面上显示的每个区域的人口数量。

也就是说,对于每个区域,我需要在其 infobox geography vcard 元素中显示人口。例如。对于 this region ,人口将为 591680


代码

在编写循环之前,我试图获取一个单独区域的人口,

url = 'https://en.wikipedia.org/wiki/Arcadia'

browser.get(url)

vcard_element = browser.find_element_by_css_selector('#mw-content-text > div > table.infobox.geography.vcard').find_element_by_xpath('tbody')

for row in vcard_element.find_elements_by_xpath('tr'):

try:
if 'Population' in row.find_element_by_xpath('th').text:
print(row.find_element_by_xpath('th').text)
except Exception:
pass

问题

代码有效。也就是说,它打印包含单词“Population”的行。

问题:我如何告诉 Selenium 获取下一行——包含实际人口数量的行?

最佳答案

使用./following::tr[1]./following-sibling::tr[1]

url = 'https://en.wikipedia.org/wiki/Arcadia'
browser=webdriver.Chrome()
browser.get(url)

vcard_element = browser.find_element_by_css_selector('#mw-content-text > div > table.infobox.geography.vcard').find_element_by_xpath('tbody')

for row in vcard_element.find_elements_by_xpath('tr'):

try:
if 'Population' in row.find_element_by_xpath('th').text:
print(row.find_element_by_xpath('th').text)
print(row.find_element_by_xpath('./following::tr[1]').text) #whole word
print(row.find_element_by_xpath('./following::tr[1]/td').text) #Only number
except Exception:
pass

控制台输出:

Population (2011)
• Total 86,685
86,685

关于python - 根据当前行的值获取下一行的值 Selenium,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59269764/

52 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com