【问题标题】:Scrape all used javascripts on a website using python使用 python 抓取网站上所有使用过的 javascripts
【发布时间】:2017-11-02 13:12:23
【问题描述】:

我正在寻找一种方法来确定网站上使用的所有 javascript 的名称。不适合简单地使用请求库下载网站的源代码,因为这不会产生所有使用的 javascript。 例如,网站https://www.grantthornton.global/en/ 使用谷歌分析(analytics.js),可以看到使用 chrome 的“网络”选项卡来查看所有使用的 javascript。

但是,您无法仅通过源代码确定 analytics.js 的使用情况,因为 analytics.js 是通过 google-tag-manager 加载的。 我目前的方法是使用 selenium 加载网站并通过 browsermob-proxy 记录所有数据。然后,我可以通过检查 url 来检查所有已访问的 javascript(例如: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)

【问题讨论】:

  • 你能分享你的代码试验吗?
  • 对不起,我过早地发布了这个问题;现在附上代码。
  • 您是否想知道您的特定代码是否可以改进(可能是)或者您的方法是否合理?
  • 两者,这似乎是非常低效的,我可以想象很多边缘情况没有被考虑。有没有更优雅的方式?

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


【解决方案1】:

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

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

【讨论】:

  • 这会产生所有提供 javascripts 的 URL 的列表。不是脚本本身的名称。然而,这可以很容易地转换,因为 javascript 的名称是 URL 的结尾。感谢您提供更优雅的解决方案。
  • 只需将e.name 替换为e.name.match(/.+\/([^?]+)/)[1] 即可仅获取名称。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-09-28
  • 2013-03-31
  • 2022-10-14
  • 2016-05-27
  • 1970-01-01
  • 2022-01-08
  • 2021-04-13
相关资源
最近更新 更多