【问题标题】:How to list loaded resources with Selenium/PhantomJS?如何使用 Selenium/PhantomJS 列出加载的资源?
【发布时间】:2013-11-05 10:16:16
【问题描述】:

我想加载一个网页并列出该页面的所有加载资源(javascript/images/css)。我使用此代码加载页面:

from selenium import webdriver
driver = webdriver.PhantomJS()
driver.get('http://example.com')

上面的代码完美运行,我可以对 HTML 页面进行一些处理。问题是,我如何列出该页面加载的所有资源?我想要这样的东西:

['http://example.com/img/logo.png',
 'http://example.com/css/style.css',
 'http://example.com/js/jquery.js',
 'http://www.google-analytics.com/ga.js']

我也对其他解决方案持开放态度,例如使用 PySide.QWebView 模块。我只想列出页面加载的资源。

【问题讨论】:

  • 这也正是我需要完成的。 Ghost.py 有/有一种超级直接的方式来做到这一点,除了 Ghost.py 似乎不太好用。

标签: python selenium phantomjs qwebview


【解决方案1】:

这不是 Selenium 解决方案,但它可以很好地与 python 和 PhantomJS 配合使用。

这个想法与 Chrome 开发者工具中的“网络”选项卡中的操作完全相同。 为此,我们必须监听网页发出的每个请求。

Javascript/Phantomjs 部分

使用phantomjs,这可以使用这个脚本来完成,在你自己方便的时候使用它:

// getResources.js
// Usage: 
// ./phantomjs --ssl-protocol=any --web-security=false getResources.js your_url
// the ssl-protocol and web-security flags are added to dismiss SSL errors

var page = require('webpage').create();
var system = require('system');
var urls = Array();

// function to check if the requested resource is an image
function isImg(url) {
  var acceptedExts = ['jpg', 'jpeg', 'png'];
  var baseUrl = url.split('?')[0];
  var ext = baseUrl.split('.').pop().toLowerCase();
  if (acceptedExts.indexOf(ext) > -1) {
    return true;
  } else {
    return false;
  }
}

// function to check if an url has a given extension
function isExt(url, ext) {
  var baseUrl = url.split('?')[0];
  var fileExt = baseUrl.split('.').pop().toLowerCase();
  if (ext == fileExt) {
    return true;
  } else {
    return false;
  }
}

// Listen for all requests made by the webpage, 
// (like the 'Network' tab of Chrome developper tools)
// and add them to an array
page.onResourceRequested = function(request, networkRequest) { 
  // If the requested url if the one of the webpage, do nothing
  // to allow other ressource requests
  if (system.args[1] == request.url) {
    return;
  } else if (isImg(request.url) || isExt(request.url, 'js') || isExt(request.url, 'css')) {
    // The url is an image, css or js file 
    // add it to the array
    urls.push(request.url)
    // abort the request for a better response time
    // can be omitted for collecting asynchronous loaded files
    networkRequest.abort(); 
  }
};

// When all requests are made, output the array to the console
page.onLoadFinished = function(status) {
  console.log(JSON.stringify(urls));
  phantom.exit();
};

// If an error occur, dismiss it
page.onResourceError = function(){
  return false;
}
page.onError = function(){
  return false;
}

// Open the web page
page.open(system.args[1]);

Python 部分

现在在 python 中调用代码:

from subprocess import check_output
import json

out = check_output(['./phantomjs', '--ssl-protocol=any', \
    '--web-security=false', 'getResources.js', your_url])
data = json.loads(out)

希望对你有帮助

【讨论】:

  • 确实,但是 Selenium webdriver api 并没有让我们完全访问 phantomjs api,我编辑了我的答案来展示如何使用 python 使用这个脚本。
  • 用java怎么做?
【解决方案2】:

webdribver 中没有一个函数可以返回网页的所有资源,但你可以这样做:

from selenium.webdriver.common.by import By
images = driver.find_elements(By.TAG_NAME, "img")

脚本和链接也是如此。

【讨论】:

    【解决方案3】:

    这是一个使用 Selenium 和 ChromeDriver 的纯 Python 解决方案。

    它是如何工作的:

    1. 首先,我们创建一个在 localhost 上侦听的简约 HTTP 代理。这个代理负责打印 Selenium 生成的任何请求。
      注意:我们使用 multiprocessing 来避免将脚本一分为二,但您也可以将代理部分放在单独的脚本中)
    2. 然后我们创建webdriver,配置第 1 步中的代理,从标准输入中读取 URL 并串行加载它们。
      并行加载 URL 留给读者作为练习;)

    要使用此脚本,您只需在标准输入中键入 URL,然后它会在标准输出中输出已加载的 URL(带有各自的引荐来源网址)。 代码:

    #!/usr/bin/python3
    
    import sys
    import time
    import socketserver
    import http.server
    import urllib.request
    from multiprocessing import Process
    
    from selenium import webdriver
    
    PROXY_PORT = 8889
    PROXY_URL = 'localhost:%d' % PROXY_PORT
    
    class Proxy(http.server.SimpleHTTPRequestHandler):
        def do_GET(self):
            sys.stdout.write('%s → %s\n' % (self.headers.get('Referer', 'NO_REFERER'), self.path))
            self.copyfile(urllib.request.urlopen(self.path), self.wfile)
            sys.stdout.flush()
    
        @classmethod
        def target(cls):
            httpd = socketserver.ThreadingTCPServer(('', PROXY_PORT), cls)
            httpd.serve_forever()
    
    p_proxy = Process(target=Proxy.target)
    p_proxy.start()
    
    
    webdriver.DesiredCapabilities.CHROME['proxy'] = {
        "httpProxy":PROXY_URL,
        "ftpProxy":None,
        "sslProxy":None,
        "noProxy":None,
        "proxyType":"MANUAL",
        "class":"org.openqa.selenium.Proxy",
        "autodetect":False
    }
    
    driver = webdriver.Chrome('/usr/lib/chromium-browser/chromedriver')
    for url in sys.stdin:
        driver.get(url)
    driver.close()
    del driver
    p_proxy.terminate()
    p_proxy.join()
    # avoid warnings about selenium.Service not shutting down in time
    time.sleep(3)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-11-23
      • 2017-07-05
      • 2017-07-04
      • 1970-01-01
      • 2013-10-06
      • 2012-03-18
      • 1970-01-01
      相关资源
      最近更新 更多