【问题标题】:Using BeautifulSoup, is it possible to move to the parent tag when using the search for text function?使用 BeautifulSoup,是否可以在使用搜索文本功能时移动到父标签?
【发布时间】:2016-10-11 15:28:27
【问题描述】:

当只有文本是公共标识符时,是否可以从 DOM 中的当前位置上下移动?

<div>changing text</div>
    <div>fixed text</div>

搜索fixed text 并向上移动到父div 时如何获取文本changing text

我尝试了什么:

x = soup.body.findAll(text=re.compile('fixed text')).parent

AttributeError: 'ResultSet' object has no attribute 'parent'

【问题讨论】:

  • 你的尝试发生了什么?
  • 我收到一个错误:AttributeError: 'ResultSet' object has no attribute 'parent'....抱歉,我将其添加到问题中
  • findAll 返回ResultSet - 元素列表。您想对结果集中的元素进行操作。
  • @BitByBit 检查我编辑的答案
  • @TalesPadua 这行不通,因为即使他们仍然只是兄弟姐妹,您仍然必须先搬到父母身边。我不知道为什么!

标签: python beautifulsoup


【解决方案1】:

这个程序可能会做你想做的事:

from bs4 import BeautifulSoup
import re

html = '<body><div>changing text</div><div>fixed text</div><body>'

soup = BeautifulSoup(html)

x = soup.body.findAll(text=re.compile('fixed text'))[0].parent.previous_sibling

assert x.text == 'changing text'

【讨论】:

  • 我喜欢,但考虑到这是find_all,列表理解可能是为了divs = [elem.previous_sibling for elem in soup.body.findAll(text=re.compile('fixed text'))]
  • 它有效,但我不太明白。正如 Tales 所提到的,这些实际上是兄弟姐妹,所以我们为什么要在这里让父母参与进来?
  • @BitByBit - 如果他们是兄弟姐妹,它不应该工作。但是我们没有足够的文档来解决这个问题。我发布了一个示例来制作 div 列表...这行得通吗?
  • .parent 是必需的,因为 findAll 返回字符串节点,而不是 &lt;div&gt; 节点。如果您希望findAll 返回&lt;div&gt; 节点,请尝试:x = soup.body.findAll('div', text=re.compile('fixed text'))[0].previous_sibling
  • @tdelaney 你很接近,Rob 是对的。 divs = [elem.parent.previous_sibling for elem in soup.body.findAll(text=re.compile('fixed text'))]
【解决方案2】:

您遇到的错误是由于在结果集中调用parent,结果列表。如果您需要多个结果,请尝试:

x = soup.body.find_all(text=re.compile('fixed text'))
for i in x:
    previous_div = i.previous_sibling

如果不想查找多个结果,只需将find_all改为find:

x = soup.body.find(text=re.compile('fixed text')).previous_sibling

请注意,我将 parent 替换为 previous_sibling,因为 div 处于同一级别

【讨论】:

  • 您将其更改为仅查找单个元素。 OP 正在使用findAll 并且可能想要在多个节点上进行处理。
  • 是的,但是 OP 出现的错误是由于在 ResultSet 中使用了父级。我会编辑澄清
猜你喜欢
  • 1970-01-01
  • 2021-12-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-11-04
相关资源
最近更新 更多