使用python在网站上抓取所有使用过的javascripts

时间:2017-11-02 13:12:24

标签: javascript python selenium google-analytics screen-scraping

我正在寻找一种方法来确定网站上使用的所有javascripts的名称。使用请求库简单地下载网站的源代码是不合适的,因为这不会产生所有使用的javascripts。 例如,网站https://www.grantthornton.global/en/使用Google Analytics(analytics.js),因为人们可以看到使用Chrome" Network"所有使用的javascripts的选项卡。

但是,由于analytics.js是通过google-tag-manager加载的,因此您无法单独通过sourcode确定analytics.js的使用情况。 我目前的方法是使用selenium加载网站并通过browsermob-proxy记录所有数据。然后,我可以通过检查网址检查所有已访问的javascripts(例如:https://www.google-analytics.com/analytics.js
有没有比这更好的方法:

from selenium import webdriver
from browsermobproxy import Server
import pprint, time

server = Server("browsermob-proxy-2.1.4\\bin\\browsermob-proxy")
server.start()
proxy = server.create_proxy({'captureHeaders': True, 'captureContent': True, 'captureBinaryContent': True})

service_args = ["--proxy=%s" % proxy.proxy, '--ignore-ssl-errors=yes']
driver = webdriver.PhantomJS("phantomjs-2.1.1-windows\\bin\\phantomjs", service_args=service_args)
proxy.new_har()
driver.get('URL GOES HERE')
time.sleep(3)
all_requests = [entry['request']['url'] for entry in proxy.har['log']['entries']]

pp = pprint.PrettyPrinter(indent=4)
pp.pprint(proxy.har)

修改 解决方案基于Florent B的方法。 webdriver已被chrome webdriver取代,需要下载而不是phantomjs:

from selenium import webdriver
import pprint, time

driver = webdriver.Chrome('chromedriver.exe')
driver.get("https://www.URLGOESHERE.com")
time.sleep(3)
scripts = driver.execute_script("""return window.performance.getEntriesByType("resource").filter(e => e.initiatorType === 'script').map(e => e.name.match(/.+\/([^?]+)/)[1]);""")
driver.close()

pp = pprint.PrettyPrinter(indent=4)
pp.pprint(scripts)

1 个答案:

答案 0 :(得分:0)

您还可以通过window.performance API获取所有下载的脚本:

Error:  Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.pm.ApplicationInfo android.content.Context.getApplicationInfo()' on a null object reference
    at android.app.Notification$Builder.<init>(Notification.java:2386)
    at android.app.Notification$Builder.<init>(Notification.java:2375)
    at android.support.v4.app.NotificationCompatApi24$Builder.<init>(NotificationCompatApi24.java:64)
    at android.support.v4.app.NotificationCompat$NotificationCompatApi24Impl.build(NotificationCompat.java:918)
    at android.support.v4.app.NotificationCompat$Builder.build(NotificationCompat.java:1844)