2009-02-28 43 views
6

如何从Python中的字符串中删除所有HTML?例如,我又怎么能:Python HTML删除

blah blah <a href="blah">link</a> 

blah blah link 

谢谢!

+0

可能会出于您的目的矫枉过正,但如果您的字符串有更复杂或格式错误的HTML,请尝试BeautifulSoup。警告:我认为它还不适用于Python 3.0。 – bernie 2009-02-28 22:51:17

回答

7

您可以使用正则表达式来去除所有标签:

>>> import re 
>>> s = 'blah blah <a href="blah">link</a>' 
>>> re.sub('<[^>]*>', '', s) 
'blah blah link' 
+0

您可以将您的正则表达式简化为'<.*?>',它将完成相同的结果,但是这与前面假设的格式正确无误。 – UnkwnTech 2009-02-28 22:45:00

+0

你需要检查报价吗?还是那些不允许?你有没有 2009-02-28 22:45:42

+0

@Unkwntech:我更喜欢<[^>] *>超过<.*?>,因为前者不需要保持回溯来找到标签的末尾。 – 2009-02-28 22:50:19

0
>>> import re 
>>> s = 'blah blah <a href="blah">link</a>' 
>>> q = re.compile(r'<.*?>', re.IGNORECASE) 
>>> re.sub(q, '', s) 
'blah blah link' 
18

当您的正则表达式解决方案撞墙时,请尝试这个超级简单(可靠)的程序BeautifulSoup

from BeautifulSoup import BeautifulSoup 

html = "<a> Keep me </a>" 
soup = BeautifulSoup(html) 

text_parts = soup.findAll(text=True) 
text = ''.join(text_parts) 
10

还有一个叫做stripogram的小型图书馆,它可以用来去除部分或全部HTML标签。所以

from stripogram import html2text, html2safehtml 
# Only allow <b>, <a>, <i>, <br>, and <p> tags 
clean_html = html2safehtml(original_html,valid_tags=("b", "a", "i", "br", "p")) 
# Don't process <img> tags, just strip them out. Use an indent of 4 spaces 
# and a page that's 80 characters wide. 
text = html2text(original_html,ignore_tags=("img",),indent_width=4,page_width=80) 

,如果你想简单地去掉所有的HTML,你通过valid_tags =()的第一个功能:

您可以使用它像这样。

您可以找到documentation here

5

Regexs,BeautifulSoup,html2text 不起作用如果属性中有'>'。请参阅Is “>” (U+003E GREATER-THAN SIGN) allowed inside an html-element attribute value?

“基于HTML/XML解析器”的解决方案可能有助于解决此类情况,例如,stripogramsuggested by @MrTopf确实有效。

这里的ElementTree为基础的解决方案:

####from xml.etree import ElementTree as etree # stdlib 
from lxml import etree 

str_ = 'blah blah <a href="blah">link</a> END' 
root = etree.fromstring('<html>%s</html>' % str_) 
print ''.join(root.itertext()) # lxml or ElementTree 1.3+ 

输出:

blah blah link END 
1

我刚才写的。我需要它。它使用html2text并采用文件路径,尽管我更喜欢URL。 html2text的输出存储在TextFromHtml2Text.text中 将其打印出来并存储起来,并将其输入到您的宠物金丝雀中。

import html2text 
class TextFromHtml2Text: 

    def __init__(self, url = ''): 
     if url == '': 
      raise TypeError("Needs a URL") 
     self.text = "" 
     self.url = url 
     self.html = "" 
     self.gethtmlfile() 
     self.maytheswartzbewithyou() 

    def gethtmlfile(self): 
     file = open(self.url) 
     for line in file.readlines(): 
      self.html += line 

    def maytheswartzbewithyou(self): 
     self.text = html2text.html2text(self.html) 
1

有一个简单的方法是:

def remove_html_markup(s): 
    tag = False 
    quote = False 
    out = "" 

    for c in s: 
      if c == '<' and not quote: 
       tag = True 
      elif c == '>' and not quote: 
       tag = False 
      elif (c == '"' or c == "'") and tag: 
       quote = not quote 
      elif not tag: 
       out = out + c 

    return out 

的想法是在这里解释:http://youtu.be/2tu9LTDujbw

你可以看到它在这里工作:http://youtu.be/HPkNPcYed9M?t=35s

PS - 如果你对类感兴趣(关于使用python进行智能调试)我给你一个链接:http://www.udacity.com/overview/Course/cs259/CourseRev/1。免费!

不客气! :)