我需要两个元素成一个字符串中的文本:
source_code = """<span class="UserName"><a href="#">Martin Elias</a></span>"""
>>> text
'Martin Elias'
我怎么能做到这一点?
我需要两个元素成一个字符串中的文本:
source_code = """<span class="UserName"><a href="#">Martin Elias</a></span>"""
>>> text
'Martin Elias'
我怎么能做到这一点?
我搜索“蟒蛇解析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
现在,你应该能够很容易地从这些名单中提取数据。 我希望这有助于!
我建议使用Python 美丽的汤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'
安装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
您也可以尝试使用html5lib和XPath, 有关于它在这里一个很好的问题 ,这个问题的答案有一个重要的细节( namespaceHTMLElements
)要记住,使html5lib像预期的那样。 我浪费了这么多时间的努力得到它的工作,因为我忽略了,我需要改变这种状况。