Python 3 BeautifulSoup4 在源页面中搜索文本
Python 3 BeautifulSoup4 search for text in source page
我想在源代码中搜索所有“1”并打印“1”的位置 例如:<div id="yeahboy">1</div>
“1”可以替换为任何其他字符串。我想查看该字符串周围的标签。
考虑这个 context 例如 * :
from bs4 import BeautifulSoup
html = """<root>
<div id="yeahboy">1</div>
<div id="yeahboy">2</div>
<div id="yeahboy">3</div>
<div>
<span class="nested">1</span>
</div>
</root>"""
soup = BeautifulSoup(html)
您可以使用 find_all()
传递 parameter True
to indicate that you want only element nodes (instead of the child text nodes), and parameter text="1"
来表示您想要的元素的文本内容必须等于“1” - 或者您要搜索的任何其他文本 - :
for element1 in soup.find_all(True, text="1"):
print(element1)
输出:
<div id="yeahboy">1</div>
<span class="nested">1</span>
*) 对于OP:对于以后的问题,尽量给出上下文,就像上面的上下文示例一样。这将使您的问题更 具体 并且更容易回答 - 因为人们不必自己创建上下文,这可能与您实际遇到的情况无关.
我想在源代码中搜索所有“1”并打印“1”的位置 例如:<div id="yeahboy">1</div>
“1”可以替换为任何其他字符串。我想查看该字符串周围的标签。
考虑这个 context 例如 * :
from bs4 import BeautifulSoup
html = """<root>
<div id="yeahboy">1</div>
<div id="yeahboy">2</div>
<div id="yeahboy">3</div>
<div>
<span class="nested">1</span>
</div>
</root>"""
soup = BeautifulSoup(html)
您可以使用 find_all()
传递 parameter True
to indicate that you want only element nodes (instead of the child text nodes), and parameter text="1"
来表示您想要的元素的文本内容必须等于“1” - 或者您要搜索的任何其他文本 - :
for element1 in soup.find_all(True, text="1"):
print(element1)
输出:
<div id="yeahboy">1</div>
<span class="nested">1</span>
*) 对于OP:对于以后的问题,尽量给出上下文,就像上面的上下文示例一样。这将使您的问题更 具体 并且更容易回答 - 因为人们不必自己创建上下文,这可能与您实际遇到的情况无关.