我需要通过其文本的一部分获取 HTML 标签。我找到了一些解决方案,但对我来说效果不佳。
from bs4 import BeautifulSoup
import re
soup = BeautifulSoup("""
<table>
<tbody>
<tr>
<td style="width: 100px; height: 20px">
<div style="font-size: 8.7pt">
Арт.:
<span id="ContentPlaceHolder1_ContentPlaceHolder1_DataList2_Label12_0"> 1185A</span>
</div>
<div style="font-size: 12pt; font-weight: bold;">
<span id="ContentPlaceHolder1_ContentPlaceHolder1_DataList2_LoginView3_0_Label12_0">I_CAN_GET_THIS other text</span>
I CAN NOT GET THIS?.
</div>
</td>
</tr>
</tbody>
</table>
""", 'lxml')
print(soup.find('span', text=re.compile('I_CAN_GET_THIS')))
print(soup.find('div', text=re.compile('I_CAN_NOT_GET_THIS')))
>>> <span id="ContentPlaceHolder1_ContentPlaceHolder1_DataList2_LoginView3_0_Label12_0">I_CAN_GET_THIS other text</span>
>>> None
所以我无法理解为什么它在第二种情况下不起作用以及我应该做什么才能使它起作用? 谢谢
最佳答案
text
参数(现已重命名为 string
但仍受支持)将使用 .string
attribute如果有多个子元素,该元素将变为 None
:
If a tag contains more than one thing, then it’s not clear what .string should refer to, so .string is defined to be None
这正是您的目标 div
元素的情况 - 它有一个 span
子节点和一个文本节点。
相反,您可以找到文本节点,然后获取其父节点:
soup.find(text=re.compile('I CAN NOT GET THIS')).parent
或者,使用 searching function你会在哪里使用 .get_text()
它结合了 child 文本:
soup.find(lambda tag: tag.name == 'div' and 'I CAN NOT GET THIS' in tag.get_text())
关于regex - 如何使用正则表达式按文本查找标签?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41680838/