Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/vba/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python lxml-返回空列表_Python_Python 2.7_Screen Scraping_Lxml - Fatal编程技术网

Python lxml-返回空列表

Python lxml-返回空列表,python,python-2.7,screen-scraping,lxml,Python,Python 2.7,Screen Scraping,Lxml,在尝试从网页表中提取值时,我无法找出XPATH的错误。该方法似乎是正确的,因为我可以提取页面标题和其他属性,但我无法提取第三个值,它总是返回一个空列表 from lxml import html import requests test_url = 'SC312226' page = ('https://www.opencompany.co.uk/company/'+test_url) print 'Now searching URL: '+page data = requests.ge

在尝试从网页表中提取值时,我无法找出XPATH的错误。该方法似乎是正确的,因为我可以提取页面标题和其他属性,但我无法提取第三个值,它总是返回一个空列表

from lxml import html
import requests

test_url = 'SC312226'

page = ('https://www.opencompany.co.uk/company/'+test_url)

print 'Now searching URL: '+page

data = requests.get(page)
tree = html.fromstring(data.text)

print tree.xpath('//title/text()') # Get page title  
print tree.xpath('//a/@href') # Get href attribute of all links  
print tree.xpath('//*[@id="financial"]/table/tbody/tr/td[1]/table/tbody/tr[2]/td[1]/div[2]/text()')
除非我遗漏了什么,否则XPATH似乎是正确的:

我检查了Chrome控制台,显示正常!所以我不知所措

$x ('//*[@id="financial"]/table/tbody/tr/td[1]/table/tbody/tr[2]/td[1]/div[2]/text()')
[
"£432,272"
]

您应该指定元素名。如果不想指定特定的标记名,可以使用
*

print tree.xpath('//*[@id="financial"]/...')
                    ^
更新

在html文件中(仅在浏览器中呈现之前的html),没有tbody标记。因此,您需要从表达式中删除
tbody

//*[@id="financial"]/table/tr/td[1]/table/tr[2]/td[1]/div[2]/text()
使用以下同级轴的替代方法:

//div[text()="Total Assets"]/following-sibling::div/text()

试过了,还是没有乐趣。空名单,谢谢!它现在返回,但它返回以下值:[u'\xa3447']是否需要以某种方式对其进行解码?@ChrisFinlayson如果您获取一个项目并打印它,您将得到所需的内容。将其添加到print语句将正确格式化输出:
print unicodedata.normalize('NFKD',tree.xpath('/*[@id=“financial”]/table/tr/td[1]/table/tr[2]/td[1] /div[2]/text())[0]).encode('ascii','ignore')
@ChrisFinlayson,您不需要调用
unicodedata。完全规范化
encode
。打印第一项就可以了。请参见以下内容: