首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Beautifulsoup中文本搜索的即时标签

Beautifulsoup中文本搜索的即时标签
EN

Stack Overflow用户
提问于 2017-02-16 15:06:57
回答 1查看 157关注 0票数 1

我正在搜索一个特定的字符串,它应该与标签的文本值完全匹配。我如何才能只使用'RESULTS‘这个词进行搜索,并将标签'h4’返回给我?

代码语言:javascript
运行
复制
soup = BeautifulSoup('<table><tbody><tr><td class="fulltext-body-paragraph"><a name="44"></a><div class="fulltext-LEVEL1"><h4>RESULTS</h4></div></td></tr></tbody></table>')

soup.find(lambda el: el.text == 'RESULTS').name
Out: 'html' # I would like it to return 'h4'
EN

回答 1

Stack Overflow用户

发布于 2017-02-16 15:45:42

这个(https://stackoverflow.com/a/13349041/7573286)可能会解决你的问题?

代码语言:javascript
运行
复制
from bs4 import BeautifulSoup
from pprint import pprint
import re

html_text = """
<h2>this is cool #12345678901</h2>
<h2>this is nothing</h2>
<h2>this is interesting #126666678901</h2>
<h2>this is blah #124445678901</h2>
"""

soup = BeautifulSoup(html_text)

# Even though the OP was not looking for 'cool', it's more understandable to work with item zero.
pattern = re.compile(r'cool')

pprint(soup.find(text=pattern).__dict__)
#>> {'next': u'\n',
#>>  'nextSibling': None,
#>>  'parent': <h2>this is cool #12345678901</h2>,
#>>  'previous': <h2>this is cool #12345678901</h2>,
#>>  'previousSibling': None}

print soup.find('h2')
#>> <h2>this is cool #12345678901</h2>
print soup.find('h2', text=pattern)
#>> this is cool #12345678901
print soup.find('h2', text=pattern).parent
#>> <h2>this is cool #12345678901</h2>
print soup.find('h2', text=pattern) == soup.find('h2')
#>> False
print soup.find('h2', text=pattern) == soup.find('h2').text
#>> True
print soup.find('h2', text=pattern).parent == soup.find('h2')
#>> True
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/42267131

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档