Python 中使用 Selenium 单击按钮

我们可以使用 Python 中的 selenium 包在几乎所有主要的 Web 浏览器上自动执行任务。 我们可以使用此包检索元素、填写表单、单击按钮以及执行其他此类操作。

本篇文章将介绍如何在 Python 中使用 selenium 单击网页上的按钮。


Python 中使用 Selenium 单击按钮

我们将首先导入 webdriver 类并创建其对象以启动连接并打开 Web 浏览器。 我们将使用该对象在 get() 函数中检索所需的网页及其 URL。

首先,我们需要检索单击按钮所需的按钮元素。 这可以通过多种方式实现。

我们可以使用 selenium 检索具有名称、类、id 等属性的元素。

检索按钮的元素后,我们将使用 click() 函数执行单击按钮的操作。

这个逻辑在下面的代码中实现。

from selenium import webdriver
driver = webdriver.Chrome(r'C:/path/to/chromedriver.exe')
driver.get("https://www.sample_website.org/")
e = driver.find_element_by_class_name("slide-out-btn")
e.click()

在上面的示例中,我们使用 webdriver 类打开 Google Chrome 浏览器。 我们重定向到所需的网站并使用 find_element_by_class_name() 函数来获取按钮的元素。

之后,使用 click() 函数单击检索到的按钮。

猜你喜欢

转载自blog.csdn.net/fengqianlang/article/details/134241759