【问题标题】:Use find_parent result to get specific items from it使用 find_parent 结果从中获取特定项目
【发布时间】:2020-02-12 13:13:56
【问题描述】:

我正在努力寻找如何让它发挥作用。

我正在从网站上抓取少量数据,但内容放在没有类的 TABLE 中。 关于那个问题,我正在运行它来找出我要搜索的单词在哪里:

item = soup.find_all(text=re.compile('WORD'))

然后,由于其他内容在同一个父项中,我这样做:

parent = item.find_parent('tr')

现在,我得到了这样的东西:

<tr>
<td class="someclass1">WORD</td>
<td class="someclass2">TIRE</td>
<td class="someclass3">GUN</td>
<td class="someclass4">CAR</td>
<td class="someclass5">BYCICLE</td>
</tr>

既然它确实找到了 WORD 所在的好地方,我应该如何将 GUN 或 CAR 从中取出? 正如我所说,这里的主要问题是,有多个表具有相同的 TD CLASSES,但其中只有 1 个具有 WORD。该表中的内容就是我要查找的内容。

【问题讨论】:

    标签: python parsing web-scraping beautifulsoup


    【解决方案1】:

    在 bs4 4.7.1 + 中,您可以使用 :contains:has 进行隔离,因为 WORD 在表中具有给定类的元素中。在您描述的情况下,您也可以直接在table 下工作:contains,即table = soup.select_one('table:contains("WORD")')

    from bs4 import BeautifulSoup as bs
    
    html = '''
    <html>
     <head></head>
     <body>
      <table> 
       <tbody>
        <tr> 
         <td class="someclass1">WORD</td> 
        </tr> 
       </tbody>
      </table>
      <table></table> 
      <table> 
       <tbody>
        <tr> 
         <td class="someclass1">NOT_WORD</td> 
        </tr> 
       </tbody>
      </table>
      <table></table>
     </body>
    </html>
    '''
    soup = bs(html, 'lxml')
    table = soup.select_one('table:has(.someclass1:contains("WORD"))')
    print(table.text)
    

    【讨论】:

    • 我的声誉仍然很低,所以我不能投票给你的答案,但谢谢你,伙计......你是一个救生员
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-23
    • 2014-08-31
    • 2022-12-12
    • 1970-01-01
    • 1970-01-01
    • 2015-03-14
    相关资源
    最近更新 更多