簡體   English   中英

使用python抓取網站上所有使用過的javascript

[英]Scrape all used javascripts on a website using python

我正在尋找一種確定網站上使用的所有JavaScript的名稱的方法。 僅使用請求庫下載網站的源代碼是不合適的,因為這不會產生所有使用的JavaScript。 例如,網站https://www.grantthornton.global/en/使用Google Analytics(分析)(analytics.js),因為人們可以使用chrome的“網絡”標簽查看所有已使用的javascript。

但是,由於analytics.js是通過google-tag-manager加載的,因此您無法僅通過源代碼來確定analytics.js的使用情況。 我當前的方法是使用硒加載網站並通過browsermob-proxy記錄所有數據。 然后,我可以通過檢查url(例如: https : //www.google-analytics.com/analytics.js )來檢查所有已訪問的javascript。
有沒有比這更好的方法:

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)

您還可以通過window.performance API獲取所有下載的腳本:

scripts = driver.execute_script("""
  return window.performance.getEntriesByType("resource")
    .filter(e => e.initiatorType === 'script')
    .map(e => e.name);
  """)
print(scripts)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM