【问题标题】:Selenium get next tr given condition holds for previous trSelenium 获取下一个 tr 给定条件保持前一个 tr
【发布时间】:2019-06-03 04:52:10
【问题描述】:

设置

我正在尝试在 Wikipedia 上抓取法国地区的信息框。

具体来说,我需要获取每个地区的人口。对于每个地区,其人口在每个 wiki 页面的信息框中都有说明,例如见https://en.wikipedia.org/wiki/Mayotte


HTML

对于示例页面,我感兴趣的信息框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>

我需要得到人口数 256,518。


代码

我的计划是选择包含'Population' 字符串的tr,然后告诉selenium 选择它后面的tr

以下代码成功选择了包含'Population'字符串的tr

info_box = browser.find_elements_by_css_selector('.infobox').find_element_by_xpath('tbody')

for row in info_box.find_elements_by_xpath('./tr'):

    if 'Population' in row.text:

        print(row) 

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

【问题讨论】:

    标签: python html selenium html-table


    【解决方案1】:

    要提取人口,您可以简单地将带有文本的&lt;th&gt; 识别为人口,然后识别下一个&lt;tr&gt; 节点,该节点具有包含人口256,518的后代&lt;td&gt; strong>,您可以使用以下解决方案:

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

    【讨论】:

      【解决方案2】:

      无需遍历所有行。您只需要选择所需的行

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

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

      【讨论】:

        【解决方案3】:

        我认为这应该足够好

        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
        

        【讨论】:

          猜你喜欢
          • 2012-07-10
          • 2016-12-26
          • 2012-09-10
          • 2013-08-29
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-09-26
          • 2013-09-24
          相关资源
          最近更新 更多