解析HTML以获取元素内的文本

时间:2012-08-03 22:31:15

标签: python html python-2.x html-parser

我需要将两个元素中的文本放到一个字符串中:

source_code = """<span class="UserName"><a href="#">Martin Elias</a></span>"""

>>> text
'Martin Elias'

我怎么能实现这个目标?

4 个答案:

答案 0 :(得分:31)

我搜索了“python parse html”,这是第一个结果: https://docs.python.org/2/library/htmlparser.html

此代码取自python docs

from HTMLParser import HTMLParser

    # create a subclass and override the handler methods
    class MyHTMLParser(HTMLParser):
        def handle_starttag(self, tag, attrs):
            print "Encountered a start tag:", tag
        def handle_endtag(self, tag):
            print "Encountered an end tag :", tag
        def handle_data(self, data):
            print "Encountered some data  :", data

    # instantiate the parser and fed it some HTML
    parser = MyHTMLParser()
    parser.feed('<html><head><title>Test</title></head>'
                '<body><h1>Parse me!</h1></body></html>')

结果如下:

Encountered a start tag: html
Encountered a start tag: head
Encountered a start tag: title
Encountered some data  : Test
Encountered an end tag : title
Encountered an end tag : head
Encountered a start tag: body
Encountered a start tag: h1
Encountered some data  : Parse me!
Encountered an end tag : h1
Encountered an end tag : body
Encountered an end tag : html

使用它并查看HTMLParser中的代码我想出了这个:

class myhtmlparser(HTMLParser):
    def __init__(self):
        self.reset()
        self.NEWTAGS = []
        self.NEWATTRS = []
        self.HTMLDATA = []
    def handle_starttag(self, tag, attrs):
        self.NEWTAGS.append(tag)
        self.NEWATTRS.append(attrs)
    def handle_data(self, data):
        self.HTMLDATA.append(data)
    def clean(self):
        self.NEWTAGS = []
        self.NEWATTRS = []
        self.HTMLDATA = []

你可以像这样使用它:

from HTMLParser import HTMLParser

pstring = source_code = """<span class="UserName"><a href="#">Martin Elias</a></span>"""


class myhtmlparser(HTMLParser):
    def __init__(self):
        self.reset()
        self.NEWTAGS = []
        self.NEWATTRS = []
        self.HTMLDATA = []
    def handle_starttag(self, tag, attrs):
        self.NEWTAGS.append(tag)
        self.NEWATTRS.append(attrs)
    def handle_data(self, data):
        self.HTMLDATA.append(data)
    def clean(self):
        self.NEWTAGS = []
        self.NEWATTRS = []
        self.HTMLDATA = []

parser = myhtmlparser()
parser.feed(pstring)

# Extract data from parser
tags  = parser.NEWTAGS
attrs = parser.NEWATTRS
data  = parser.HTMLDATA

# Clean the parser
parser.clean()

# Print out our data
print tags
print attrs
print data

现在,您应该可以轻松地从这些列表中提取数据。我希望这有帮助!

答案 1 :(得分:22)

我建议使用Python Beautiful Soup 4库。

pip install beautifulsoup4

它使HTML解析变得非常简单。

from bs4 import BeautifulSoup
source_code = """<span class="UserName"><a href="#">Martin Elias</a></span>"""
soup = BeautifulSoup(source_code)
print soup.a.string
>>> 'Martin Elias'

答案 2 :(得分:3)

安装beautifulsoup和 你可以这样做:

from BeautifulSoup import  BeautifulSoup
source_code = '"""<span class="UserName"><a href="#">Martin Elias</a></span>"""'
soup = BeautifulSoup(source_code)
print soup.find('span',{'class':'UserName'}).text

答案 3 :(得分:1)

您还可以尝试使用html5lib和XPath,there is a good question about it here,该答案有一个重要的细节(namespaceHTMLElements),以便让html5lib按预期运行。我浪费了太多时间试图让它发挥作用,因为我忽略了我需要改变它。