如何使用 Google Chrome 的控制台执行 click()? (Javascript)

How to perform a click() using Google Chrome's Console? (Javascript)

我正在尝试制作一个 Javascript 代码来自动点击网页上的按钮,所以我试图用 Google Chrome 的控制台找出代码。这是按钮:

<a href="#" class="link">Get Link</a>

我以为我可以简单地写这个:

var button = document.getElementsByClassName('link');
button.click()

但是出现了这条消息:

"Uncaught TypeError: button.click is not a function at <anonymous>:2:8"

有什么解决办法吗?感谢您的帮助。

getElementsByClassName returns a live HTMLCollection,没有一个元素。

elements is a live HTMLCollection of found elements.

所以如果你想使用 getElementsByClassName,你需要像这样从 iterable 中获取第一项:

var button = document.getElementsByClassName('link');
button[0].click()

如果要获取单个元素,请使用document.querySelector()。这将 return 第一个找到的元素。

var button = document.querySelector('.link');
button.click()

This is a screenshot of the line I wrote

是否正确?