首页 > 解决方案 > 使用 find_parent 结果从中获取特定项目

问题描述

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

我正在从网站上抓取少量数据,但内容放在没有类的 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。该表中的内容就是我要查找的内容。

标签: pythonparsingweb-scrapingbeautifulsoup

解决方案


使用 bs4 4.7.1 +,您可以使用:contains:has基于在WORD表中具有给定类的元素中进行隔离。在您描述的情况下,您也可以:contains直接工作,tabletable = 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)

推荐阅读