使用美汤解析长期复杂的html文档时,有时需要准确地找到匹配元素的原始字符串中的位置。我不能简单地搜索字符串,因为可能有多个匹配的元素,我将失去BS4解析DOM的能力。鉴于这一最低限度的工作实例:
import bs4
html = "<div><b>Hello</b> <i>World</i></div>"
soup = bs4.BeautifulSoup(html,'lxml')
# Returns 22
print html.find("World")
# How to get this to return 22?
print soup.find("i", text="World")
如何使bs4
提取的元素返回22?
发布于 2018-08-17 05:14:43
我知道你的问题是“世界”可能被写了很多遍,但你想要获得一个特定事件的位置(不知何故,你知道如何识别)。
你可以用这个解决办法。我敢打赌还有更优雅的解决方案,但这应该会使它:
考虑到这个html:
import bs4
html = """<div><b>Hello</b> <i>World</i></div>
<div><b>Hello</b> <i>Foo World</i></div>
<div><b>Hello</b> <i>Bar World</i></div>"""
soup = bs4.BeautifulSoup(html,'lxml')
如果我们想获得Foo世界的地位,我们可以:
https://stackoverflow.com/questions/48230684
复制相似问题