Python Selenium获取下一个tr给定条件适用于上一个tr

Python Selenium获取下一个tr给定条件适用于上一个tr,python,html,selenium,html-table,Python,Html,Selenium,Html Table,设置 我正试图在维基百科上搜索法国地区的信息框 具体来说,我需要获得每个地区的人口。对于每个区域,其人口都在每个wiki页面的信息框中说明,例如,请参见 HTML 对于示例页面,我感兴趣的infobox html部分如下所示 <tr class="mergedtoprow"> <th colspan="2" style="text-align:center;text-align:left">Area <div style="font-weigh

设置

我正试图在维基百科上搜索法国地区的信息框

具体来说,我需要获得每个地区的人口。对于每个区域,其人口都在每个wiki页面的信息框中说明,例如,请参见


HTML

对于示例页面,我感兴趣的infobox html部分如下所示

<tr class="mergedtoprow">
   <th colspan="2" style="text-align:center;text-align:left">Area
       <div style="font-weight:normal;display:inline;"></div></th></tr>
<tr class="mergedrow">
   <th scope="row">&nbsp;•&nbsp;Total</th> 
       <td>374&nbsp;km<sup>2</sup> (144&nbsp;sq&nbsp;mi)</td></tr>
<tr class="mergedtoprow">
   <th colspan="2" style="text-align:center;text- align:left">
       Population 
       <div style="font-weight:normal;display:inline;">
            (2017)
            <sup id="cite_ref-census_1-0" class="reference">
                 <a href="#cite_note-census-1">[1]</a>
            </sup>
       </div>
   </th>
</tr>
<tr class="mergedrow">
   <th scope="row">&nbsp;•&nbsp;Total</th>
   <td>256,518</td>
</tr>

现在!如何告诉Selenium在选择的
tr
之后选择
tr

我认为这应该足够好了

info_box = browser.find_elements_by_css_selector('.infobox').find_element_by_xpath('tbody')
tr_data = info_box.find_elements_by_xpath('./tr')
for row in range(0, len(tr_data)):

    if 'Population' in tr_data[row].text:

        print(tr_data[row + 1].text) 
        break

不需要迭代所有行。您只需要选择所需的行

尝试此代码行以获得所需的输出:

population = driver.find_element_by_xpath('//tr[contains(th, "Population")]/following-sibling::tr/td').text
print(population)
#  256,518

要提取填充,您只需将
文本标识为填充,并标识下一个
节点,该节点具有包含填充的后代
,您可以使用以下解决方案:

print(driver.find_element_by_xpath("//th[contains(., 'Population')]//following::tr[1]//td").get_attribute("innerHTML"))
print(driver.find_element_by_xpath("//th[contains(., 'Population')]//following::tr[1]//td").get_attribute("innerHTML"))