我想用python解析HTML
我有一个小班:我想用python解析HTML,python,html,parsing,Python,Html,Parsing,我有一个小班: class HTMLTagStripper(HTMLParser): def __init__(self): self.reset() self.fed = [] def handle_data(self, data): self.fed.append(data) def handle_starttag(self, tag, attrs): if tag == 'a': retu
class HTMLTagStripper(HTMLParser):
def __init__(self):
self.reset()
self.fed = []
def handle_data(self, data):
self.fed.append(data)
def handle_starttag(self, tag, attrs):
if tag == 'a':
return attrs[0][1]
def get_data(self):
return ''.join(self.fed)
解析此HTML代码:
长文本
点击
这是我得到的结果:长文本单击此处
但是我想得到:
长文本点击somelink.com
有什么方法可以做到这一点吗?看看。。它将做到这一点,甚至更多
或者,您可以使用正则表达式/字符串操作删除所需的数据。从长远来看,使用像BeautifulSoup这样的东西会有回报,特别是如果你希望做更多的话
这里有一种方法可以使用BeautifulSoup提取HTML数据中的单个/唯一链接(我不是这方面的专家,所以可能还有其他更好的方法-欢迎建议/更正)
从美化组导入美化组
s=”“”
长文本
点击
"""
汤=美汤(s)
你的链接=soup.find('a',href=True)['href']
打印“长文本点击”链接
将打印:
长文本单击somelink.com
这对您不起作用:
x = re.compile(r'<.*?>')
stripped = x.sub('', html)
x=re.compile(r'')
剥离=x.sub(“”,html)
因为您还想从html标记中提取一些属性(如href)
正如列文所指出的:你应该选择BeautifulSoup。取代这个:
def handle_starttag(self, tag, attrs):
if tag == 'a':
return attrs[0][1]
为此:
def handle_starttag(self, tag, attrs):
if tag == 'a':
value = dict(attrs).get("href", None)
if value:
# add extra spaces since you dont sanitize
# them in get_data
self.fed.append(" %s " % value)
应该是一种工作。或者不,取决于html源代码。这就是为什么我们有BeatifulSoup。我实际上是在检查这个新的html解析器库,并提出了这个解决方案:
from htmldom import htmldom
dom = htmldom.HtmlDom().createDom( """<div id="footer">
<p>long text.</p>
<p>click <a href="somelink.com">here</a>
</div>""");
nodes = dom.find( "p" ).children( all_children = True ) # this makes all text nodes to be in the set.
for node in nodes:
if node._is( "a" ):
print( node.attr( "href" ).strip() )
elif node._is( "text" ):
print( node.getNode().text, end = '', sep = ' ' )
从htmldom导入htmldom
dom=htmldom.htmldom().createDom(“”)
长文本
点击
""");
nodes=dom.find(“p”).children(all_children=True)#这使得所有文本节点都在集合中。
对于节点中的节点:
如果节点是(“a”):
打印(node.attr(“href”).strip())
elif节点是(“文本”):
打印(node.getNode().text,end='',sep='')
您可以从python包index:下载该库,该库在Python3.x上工作,库的文档不是很好,但可以理解。希望你喜欢答案:)如果有意愿。。。我知道我会因为这个建议而被批评,但是如果你想做的只是删除标签,你可以使用正则表达式:-)或者其他为它设计的库。啊,对了。谢谢你指出这一点。在这个问题上没有注意到。@ USS1307624,如果这解决了你的问题,请考虑我的答案旁边。它会将此问题标记为已解决,并奖励我们两人一些代表积分。谢谢。你可以在
from htmldom import htmldom
dom = htmldom.HtmlDom().createDom( """<div id="footer">
<p>long text.</p>
<p>click <a href="somelink.com">here</a>
</div>""");
nodes = dom.find( "p" ).children( all_children = True ) # this makes all text nodes to be in the set.
for node in nodes:
if node._is( "a" ):
print( node.attr( "href" ).strip() )
elif node._is( "text" ):
print( node.getNode().text, end = '', sep = ' ' )