31

我需要将两个元素内的文本转换成一个字符串:

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

>>> text
'Martin Elias'

我怎么能做到这一点?

4

4 回答 4

44

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

此代码取自 python 文档

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

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

于 2012-08-03T23:37:35.820 回答
34

我推荐使用 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'
于 2012-08-03T23:46:52.810 回答
5

安装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
于 2012-08-04T09:26:12.883 回答
1

您也可以尝试使用 html5lib 和 XPath,这里有一个很好的问题,该答案有一个重要的细节 ( namespaceHTMLElements) 需要记住,以使 html5lib 按预期运行。我浪费了很多时间试图让它工作,因为我忽略了我需要改变它。

于 2012-08-04T09:22:29.037 回答