2010-05-08 42 views

回答

1

我會盡力採取了刺這個:

如果你想使用jQuery的圖像的URL 你可以使用這樣的方法:如果你不想從網絡加載jQuery的

import sys 
from PyQt4.QtCore import * 
from PyQt4.QtGui import * 
from PyQt4.QtWebKit import * 
app = QApplication(sys.argv) 
web = QWebView() 
web.load(QUrl("http://google.com")) 
frame = web.page().mainFrame() 

web.show() 

def loadFinished(ok): 
    print 'loaded' 
    frame.evaluateJavaScript(""" 
    //this is a hack to load an external javascript script 
    //credit to Vincent Robert from http://stackoverflow.com/questions/756382/bookmarklet-wait-until-javascript-is-loaded 
    function loadScript(url, callback) 
{ 
     var head = document.getElementsByTagName("head")[0]; 
     var script = document.createElement("script"); 
     script.src = url; 
     // Attach handlers 
     var done = false; 
     script.onload = script.onreadystatechange = function() 
     { 
       if(!done && (!this.readyState 
             || this.readyState == "loaded" 
             || this.readyState == "complete")) 
       { 
         done = true; 
         // Continue your code 
         callback(); 
       } 
     }; 

     head.appendChild(script); 
} 

// This code loads jQuery and executes some code when jQuery is loaded, using above trick 
loadScript("http://code.jquery.com/jquery-latest.js", function(){ 
    //we can inject an image into the page like this: 
    $(document.body).append('<img src="http://catsplanet.files.wordpress.com/2009/08/kitten_01.jpg" id="kitten"/>'); 
    //you can get the url before the image loads like so: 
     //detectedKittenImageUrl = $('#kitten').attr('src'); 
     //alert('detectedKittenImageUrl = ' + detectedKittenImageUrl); 
    //but this is how to get the url after it is loaded, by using jquery to bind to it's load function: 
    $('#kitten').bind('load',function(){ 
     //the injected image has loaded 
     detectedKittenImageUrl = $('#kitten').attr('src'); 
     alert('detectedKittenImageUrl = ' + detectedKittenImageUrl); 
     //Google's logo image url is provided by css as opposed to using an IMG tag: 
     //it has probabled loaded befor the kitten image which was injected after load 
     //we can get the url of Google's logo like so: 
     detectedGoogleLogoImageUrl = $('#logo').css('background-image'); 
     alert('detectedGoogleLogoImageUrl = ' + detectedGoogleLogoImageUrl); 
    }); 

}); 

    """) 

app.connect(web, SIGNAL("loadFinished(bool)"), loadFinished) 

sys.exit(app.exec_()) 

Ë ACH時候,你可以下載的jQuery再注入這樣的:

jQuerySource = open('jquery.min.js').read() 
frame.evaluateJavaScript(jQuerySource) 

你也可以不使用jQuery可言,但它往往使操作更容易,這取決於你想要做什麼。

如果要將圖像內容作爲位圖獲取而不是網址,則可能使用HTML畫布對象,我不確定是否會遇到跨域安全問題。 另一種方法是使用pyQT來獲取圖像。如果你有一個alpha透明的PNG,這將會更復雜,但是對於不透明的JPEG,例如它會更容易。 你可以谷歌周圍的一些網頁截圖代碼如何做到這一點,或者你可以從Python找到的網址下載。 一旦您在Javascript中使用了url變量,您可能必須使用this great slideshow上的跨邊界技術將變量獲取到Python中進行下載。

http://www.sivachandran.in/index.php/blogs/web-automation-using-pyqt4-and-jquery也可能是有用的示例代碼。