【问题标题】:Using BeautifulSoup and python regexp to search html for string and add some tags使用 BeautifulSoup 和 python 正则表达式在 html 中搜索字符串并添加一些标签
【发布时间】:2015-06-09 08:55:24
【问题描述】:

我正在使用 BeautifulSoup 在特定页面上查找用户输入的单词,并突出显示所有这些单词。例如,我想突出显示页面上的所有单词“财务” 'https://support.google.com/finance/?hl=en&ei=VC8QVaH0N-acwgP36IG4AQ'。

#!/usr/bin/python
# charset=utf-8

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)

matches = soup.body(text='Finance')
for match in matches:
    match.wrap(soup.new_tag('span', style="background-color:#FE00FE"))
print soup

【问题讨论】:

  • 试试soup.body.findAll(text='Finance')。它对你有用吗?
  • this SO post 能解决您的问题吗?如果是,这个问题是重复的。
  • 不,同样只有第一个单词“财务”在结果文件中突出显示。在他的问题中,您想查看字符串“Python”是否位于页面上(一次或多次)。但我需要突出显示页面上的每个单词。
  • 您正在搜索的文本恰好是“财务”一词。您想搜索所有包含该词的文本。用突出显示的单词替换单词也有点复杂,因为您必须将字符串拆分为单词之前、之间和之后的部分(如果一个字符串中出现多次)。

标签: python regex beautifulsoup


【解决方案1】:

我发现这个正则表达式变体用于单词突出显示。但结果文档包含损坏的 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-11-16
    • 1970-01-01
    • 2014-02-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多