【发布时间】:2018-07-16 05:44:25
【问题描述】:
我正在尝试匹配 HTML 文档中的字符串并特别突出显示它。 我使用 BeautifulSoup 和 html.parser。
到目前为止,我尝试的是使用 find_all() 并传递要匹配的字符串,但它没有帮助,因为它返回元素中存在的整个文本。
我希望您指导我如何定位文档中的特定字符串并突出显示它。
例如:标记:
<p>Lorem is simply dummy text of the printing and typesetting industry.</p>
<p>Lorem has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it
高亮后:标记:
<p><mark>Lorem</mark> is simply dummy text of the printing and typesetting industry.</p>
<p><mark>Lorem</mark> has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it
预期输出:
Lorem 只是印刷和排版行业的虚拟文本。
Lorem 自 1500 年代以来一直是行业的标准虚拟文本,当时一位不知名的打印机采用了一种类型的厨房并将其打乱
如果我能得到一个字符串数组,我可以用标记标签替换它。
beautifulsoup 做到了这么远:
import urllib.request
import re
from bs4 import BeautifulSoup
sauce = urllib.request.urlopen('http://courseweb.stthomas.edu/mjodonnell/cojo258/resume/simple_code.html').read()
soup = BeautifulSoup(sauce, 'html.parser')
body = soup.find('body')
results = body.find_all(text=re.compile(r'bastyr', re.I))
print(results)
【问题讨论】:
-
阐述你的“突出”
-
@RomanPerekhrest 我编辑了问题。
标签: python python-3.x beautifulsoup html-parsing