使用BeautifulSoup和python regexp在html中搜索字符串并添加一些标记
我使用BeautifulSoup在特定页面上查找用户输入的单词,并突出显示所有这些单词。例如,我想突出显示页面上的所有单词“Finance” ''使用BeautifulSoup和python regexp在html中搜索字符串并添加一些标记,python,regex,beautifulsoup,Python,Regex,Beautifulsoup,我使用BeautifulSoup在特定页面上查找用户输入的单词,并突出显示所有这些单词。例如,我想突出显示页面上的所有单词“Finance” '' 我发现这个用于单词突出显示的regex变体。但结果文档中包含损坏的javascript import urllib2 import re from bs4 import BeautifulSoup html = urllib2.urlopen('https://support.google.com/finance/?hl=en&ei=VC8
我发现这个用于单词突出显示的regex变体。但结果文档中包含损坏的javascript
import urllib2
import re
from bs4 import BeautifulSoup
html = urllib2.urlopen('https://support.google.com/finance/?hl=en&ei=VC8QVaH0N-acwgP36IG4AQ').read()
soup = BeautifulSoup(html)
for text in soup.body.findAll(text=True):
if re.search(r'inance\b',text):
new_html = "<p>"+re.sub(r'(\w*)inance\b', r'<span style="background-color:#FF00FF">\1inance</span>', text)+"</p>"
new_soup = BeautifulSoup(new_html)
text.parent.replace_with(new_soup.p)
print soup
导入urllib2
进口稀土
从bs4导入BeautifulSoup
html=urllib2.urlopen('https://support.google.com/finance/?hl=en&ei=VC8QVaH0N-acwgP36IG4AQ')。读取()
soup=BeautifulSoup(html)
对于soup.body.findAll中的文本(text=True):
如果重新搜索(r'inance\b',文本):
新建html=“”+re.sub(r'(\w*)财务/b',r'\1inance',text)+“”
新汤=美汤(新汤html)
text.parent.replace_为(new_soup.p)
印花汤
试试soup.body.findAll(text='Finance')
。它对你有用吗?能解决你的问题吗?如果是,则此问题重复。否,结果文件中仅突出显示第一个单词“Finance”。在他的问题中,他想知道字符串“Python”是否位于页面上(一次或多次)。但我需要突出显示页面上的每个单词。您正在搜索的文本正是单个单词“金融”。您希望搜索包含该单词的所有文本。用突出显示的单词替换单词也有点复杂,因为您必须将字符串拆分为单词之前、之间和之后的部分(如果一个字符串中出现多个)。
import urllib2
import re
from bs4 import BeautifulSoup
html = urllib2.urlopen('https://support.google.com/finance/?hl=en&ei=VC8QVaH0N-acwgP36IG4AQ').read()
soup = BeautifulSoup(html)
for text in soup.body.findAll(text=True):
if re.search(r'inance\b',text):
new_html = "<p>"+re.sub(r'(\w*)inance\b', r'<span style="background-color:#FF00FF">\1inance</span>', text)+"</p>"
new_soup = BeautifulSoup(new_html)
text.parent.replace_with(new_soup.p)
print soup