2017-08-07 44 views
3

我已经用python与xpath一起编写了一个脚本来从含有xml内容的站点中刮取链接。因为我从来没有使用过XML,所以我无法弄清楚我犯的错误。在此先感谢您提供解决方法。以下是我与努力:无法解析来自xml内容的链接

import requests 
from lxml import html 

response = requests.get("https://drinkup.london/sitemap.xml").text 
tree = html.fromstring(response) 
for item in tree.xpath('//div[@class="expanded"]//span[@class="text"]'): 
    print(item) 

XML内容中哪些链接是:

<div xmlns="http://www.w3.org/1999/xhtml" class="collapsible" id="collapsible4"><div class="expanded"><div class="line"><span class="button collapse-button"></span><span class="html-tag">&lt;url&gt;</span></div><div class="collapsible-content"><div class="line"><span class="html-tag">&lt;loc&gt;</span><span class="text">https://drinkup.london/</span><span class="html-tag">&lt;/loc&gt;</span></div></div><div class="line"><span class="html-tag">&lt;/url&gt;</span></div></div><div class="collapsed hidden"><div class="line"><span class="button expand-button"></span><span class="html-tag">&lt;url&gt;</span><span class="text">...</span><span class="html-tag">&lt;/url&gt;</span></div></div></div> 

在执行时抛出的错误下面给出:

value = etree.fromstring(html, parser, **kw) 
    File "src\lxml\lxml.etree.pyx", line 3228, in lxml.etree.fromstring (src\lxml\lxml.etree.c:79593) 
    File "src\lxml\parser.pxi", line 1843, in lxml.etree._parseMemoryDocument (src\lxml\lxml.etree.c:119053) 
ValueError: Unicode strings with encoding declaration are not supported. Please use bytes input or XML fragments without declaration. 
+0

您正在将'response'变量分配给'requests.get'中的'text'属性,它将是一个unicode字符串,因此是错误。使用'content'属性代替'text' – peterfields

回答

2

切换到.content which returns bytes instead of .text which returns unicode

import requests 
from lxml import html 


response = requests.get("https://drinkup.london/sitemap.xml").content 
tree = html.fromstring(response) 
for item in tree.xpath('//url/loc/text()'): 
    print(item) 

请注意固定的XPath表达式。

+0

你真是太棒了,先生alecxe。每当我遇到麻烦时,你就在那里。它像魔术一样工作。非常感谢。 – SIM