【问题标题】:Execute JavaScript commands in Chrome Console from Java App从 Java 应用程序在 Chrome 控制台中执行 JavaScript 命令
【发布时间】:2019-08-10 07:51:50
【问题描述】:

我想创建一个简单的应用程序,它将在特定页面上的 Chrome 控制台中执行 JavaScript 命令并返回输出。

也就是说,我想从当前页面获取所有可访问的链接。我可以通过在 Chrome 控制台中运行以下命令来做到这一点:

urls = $$('a'); for (url in urls) console.log(urls[url].href);

它将返回一组链接作为输出,我希望能够在我的应用程序中对其进行处理。

我可以从 Chrome 控制台手动运行它,但我想自动执行此任务,因为我有很多链接可以使用。

伪代码如下:

function runCommandOnSite(command, site) { ... }

function main() {
  let site = "facebook.com";
  let command = "urls = $$('a'); for (url in urls) console.log(urls[url].href)";
  let result_links = runCommandOnSite(site, command);
  console.log(result_links);
}

注意:任何可以从 Linux 桌面运行的编程语言都是可以接受的。

【问题讨论】:

    标签: javascript java python url google-chrome-devtools


    【解决方案1】:

    听起来您想抓取网页并获取该网页中的所有 URL。每当您遇到此类问题时,请始终搜索任何首选语言的 Web Crawler 示例。

    下面给出了一些从给定网页中抓取 URL 集的示例。当然,您可能需要对输出进行一些过滤。不过,玩玩看看……

    Python 3 - 美丽的汤 4

    from bs4 import BeautifulSoup
    from urllib.request import urlopen
    import ssl
    
    # to open up HTTPS URLs
    gcontext = ssl.SSLContext()
    
    # You can give any URL here. I have given the Stack Overflow homepage
    url = 'https://stackoverflow.com'
    data = urlopen(url, context=gcontext).read()
    
    page = BeautifulSoup(data, 'html.parser')
    
    for link in page.findAll('a'):
        l = link.get('href')
        print(l)
    

    Java - JSoup

    看看this example

    Node JS - Cheerio

    看看this example

    使用 Selenium Web 驱动程序 - 适用于大多数编程语言

    我不会解释这部分,因为它太宽泛了,超出了这个答案的范围。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-10-08
      • 2016-05-20
      • 1970-01-01
      • 2014-12-17
      • 1970-01-01
      • 1970-01-01
      • 2023-04-08
      相关资源
      最近更新 更多