0

我正在使用 PyQt 和美丽汤的组合从网页中抓取数据。PyQt 被用作 Python 和 Javascript 之间的解释器。我正在调用“onclick”事件并尝试在“click”事件后将该 html 提供给 Beautiful soup。以下是参考代码:

import csv
import urllib2
import sys
import time
from bs4 import BeautifulSoup
from PyQt4.QtGui import *  
from PyQt4.QtCore import *  
from PyQt4.QtWebKit import *  

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://www.att.com/shop/wireless/devices/smartphones.html'  
r = Render(url)
jsClick = """var evObj = document.createEvent('MouseEvents');
             evObj.initEvent('click', true, true );
             this.dispatchEvent(evObj);
             """

allSelector = "a#deviceShowAllLink" 
allButton   = r.frame.documentElement().findFirst(allSelector)
allButton.evaluateJavaScript(jsClick) 
html = allButton.frame.toHtml()


page = html
soup = BeautifulSoup(page)
soup.prettify()
with open('Smartphones_26decv2.0.csv', 'wb') as csvfile:
    spamwriter = csv.writer(csvfile, delimiter=',')
    spamwriter.writerow(["Date","Day of Week","Device Name","Price"])
    items = soup.findAll('a', {"class": "clickStreamSingleItem"},text=True)
    prices = soup.findAll('div', {"class": "listGrid-price"})
    for item, price in zip(items, prices):
        textcontent = u' '.join(price.stripped_strings)
        if textcontent:            
            spamwriter.writerow([time.strftime("%Y-%m-%d"),time.strftime("%A") ,unicode(item.string).encode('utf8').strip(),textcontent])

现在运行这个之后,我得到下面提到的错误:

File "D:\Microsoft\Pricing\2012-12-26\AT&T_attempt2code.py", line 32, in <module>
    html = allButton.frame.toHtml()
AttributeError: 'QWebElement' object has no attribute 'frame'

请帮助我解决这个问题并原谅我的无知,因为我是编程新手。

4

1 回答 1

0

如错误消息中所述,问题出在以下行:

html = allButton.frame.toHtml()

allButton没有frame属性,因为它是QWebElement(其定义上的转换序列是Render-> QWebFrame-> QWebElement-> QWebElement)的一个实例。

在您的代码中,frame属性是在Render._loadFinished方法中定义的,因此只有r对象具有frame属性。

如果您将html定义更改为:

html = r.frame.toHtml()

或者:

html = allButton.webFrame().toHtml()
于 2012-12-26T15:16:20.407 回答