2017-06-02 64 views
0

序言:

I followed this guide从LXML树中提取数据

遗憾的是,它不能完全工作,因此我无法从lxml树中提取我希望的数据。我对这个具体案件并不特别感兴趣;我正在寻找更一般的答案。

import sys 
from PyQt4.QtGui import * 
from PyQt4.QtCore import * 
from PyQt4.QtWebKit import * 
from lxml import html 

class Render(QWebPage): 
    def __init__(self, url): 
    self.app = QApplication(sys.argv) 
    QWebPage.__init__(self) 
    self.loadFinished.connect(self._loadFinished) 
    self.mainFrame().load(QUrl(url)) 
    self.app.exec_() 

    def _loadFinished(self, result): 
    self.frame = self.mainFrame() 
    self.app.quit() 

url = 'http://pycoders.com/archive/' 
#This does the magic.Loads everything 
r = Render(url) 
#result is a QString. 
result = r.frame.toHtml() 
#QString should be converted to string before processed by lxml 
formatted_result = str(result.toAscii()) 

#Next build lxml tree from formatted_result 
tree = html.fromstring(formatted_result) 

该指南继续这样做:

archive_links = tree.xpath('//divass="campaign"]/a/@href') 

这将导致一个错误:

Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
    File "src\lxml\lxml.etree.pyx", line 1587, in lxml.etree._Element.xpath (src\lxml\lxml.etree.c:59353) 
    File "src\lxml\xpath.pxi", line 307, in lxml.etree.XPathElementEvaluator.__call__ (src\lxml\lxml.etree.c:171227) 
    File "src\lxml\xpath.pxi", line 227, in lxml.etree._XPathEvaluatorBase._handle_result (src\lxml\lxml.etree.c:170184) 
lxml.etree.XPathEvalError: Invalid expression 

问题

要访问我的数据,我仍然需要使用正确的XPath的。为了测试起见,我试过使用title = tree.xpath('//title'). 这让我留下了一个<element title at 0xdf418>对象。我无法从这个对象中提取数据,即这种情况下的标题。

我已经尝试了几件事,但没有实际返回数据。

>>> title .__len__() 
1 
>>> title .__sizeof__() 
72 
>>> type(title) 
<type 'list'> 
>>>title[0] 
<element title at 0xdfc418> 

回答

1

可能是,有一个错字。试试这个:

archive_links = tree.xpath('//div[class="campaign"]/a/@href') 

或者:

archive_links = tree.xpath('//div[@class="campaign"]/a/@href') 
+0

这句法更有意义,但遗憾的是,我将返回'archive_links = []'。 –

+0

@MitchellvanZuylen,这是因为你只需要初始页面源代码就可以获得链接,你需要等到JavaScript执行完成 – Andersson

+0

根据指南,Render类等待JS执行。我误解了指南,是指导错误还是错过了“渲染”类? –