这就是我所拥有的:
r = requests.get("http://www.cnn.com/")
htmlelement = lxml.html.fromstring(r.text)
html = lxml.html.tostring(htmlelement)
tree = lxml.etree.fromstring(html)
print tree.xpath('//*[@id="cnn_maintt1imgbul"]/div/div[2]/div/h1/a')
我认为xml.html纠正了破碎的HTML?
错误是:
XMLSyntaxError:打开和结束标记不匹配:链接第32行和第75行第8行
谢谢!
答案 0 :(得分:1)
我不明白为什么你在这么远之后尝试重新整理内容:
>>> htmlelement = lxml.html.fromstring(r.text)
因为此时您只需应用xpath表达式:
>>> results = htmlelement.xpath('//*[@id="cnn_maintt1imgbul"]/div/div[2]/div/h1/a')
>>> results
[<Element a at 0x1113a1f50>]
>>> print lxml.html.tostring(results[0])
'<a href="/2014/04/26/world/asia/south-korea-ship-sinking/index.html?hpt=hp_t1" target="">SOUTH KOREAN PRIME MINISTER RESIGNS</a>'
我相信您的问题是lxml.html.tostring()
仍会生成HTML,然后您尝试使用XML解析器进行解析。