卓越飞翔博客卓越飞翔博客

卓越飞翔 - 您值得收藏的技术分享站
技术文章17011本站已运行3323

如何使用Python从Bootstrap选项卡中点击href链接?

Bootstrap 是流行的 HTML、CSS、JavaScript 框架,可帮助我们开发响应式、移动优先的前端 Web 应用程序。它提供表单、排版、导航、按钮和其他界面组件的设计模板。 Python 是操作网页内容的最佳语言。

硒库

如果我们需要使用 Python 编程来单击链接,我们应该使用 selenium 库。它是最流行的开源自动化测试工具,它使我们能够使网络浏览器自动化。

Selenium 主要用于自动化 Web 应用程序的测试目的,也用于其他目的,例如自动化重复任务和网页抓取。它支持Python、Java、C和Ruby等编程语言。可用于测试Google、Mozilla Fire Fox、safari等网络浏览器。

应遵循的步骤

以下是使用 selenium 从引导选项卡自动打开给定 href 链接的步骤。

  • 安装selenium库:首先,我们要在python环境中安装selenium库。以下是cod

'
pip install Selenium

如果安装成功,我们将得到以下输出 -

'
Collecting Selenium
  Downloading selenium-4.8.3-py3-none-any.whl (6.5 MB)
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Installing collected packages: outcome, h11, exceptiongroup, async-generator, wsproto, trio, trio-websocket, Selenium
Successfully installed Selenium-4.8.3 async-generator-1.10 exceptiongroup-1.1.1 h11-0.14.0 outcome-1.2.0 trio-0.22.0 trio-websocket-0.10.2 wsproto-1.2.0
Note: you may need to restart the kernel to use updated packages.
  • 导入 Web 驱动程序 - selenium 包用于自动化 Python 中的 Web 浏览器交互。支持多种浏览器/驱动程序(Firefox、Chrome、Internet Explorer)以及远程协议。

从 Selenium 库导入 webdriver 包。

'
from selenium import webdriver
  • 在此步骤中,我们将网站的驱动程序与 webdriver 包链接

'
web_driver = webdriver.Chrome("D://Myspace/chromedriver.exe")
  • 接下来,我们将通过分配网站链接,使用 webdriver 包的 get() 函数打开 href 链接。

'
web_driver.get("https://www.Tutorialspoint.com/")

让我们将上述所有步骤组合在一起并查看输出。

'
from selenium import webdriver
web_driver = webdriver.Chrome("D://Myspace/chromedriver.exe")
web_driver.get("https://www.Tutorialspoint.com/")
print("The website link opened")

输出

下面是上面代码的输出,当我们运行程序时,指定的链接将被打开。

如何使用Python从Bootstrap选项卡中点击href链接?

示例

以下是使用 python 从引导选项卡单击 href 链接的另一个示例。

'
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
url = "https://Tutorialspoint.com"
driver_path = "path/to/webdriver"
driver = webdriver.Chrome(driver_path)
driver.get(url)
tab_link = WebDriverWait(driver, 10).until(
    EC.presence_of_element_located((By.CSS_SELECTOR, \'a[data-toggle="tab"][href="#tab-1"]\'))
)
tab_link.click()
WebDriverWait(driver, 10).until(
    EC.presence_of_element_located((By.ID, "tab-1"))
)
link_url = driver.current_url
driver.get(link_url)
print(driver.page_source)
driver.quit()

输出

上述代码的输出如下。

如何使用Python从Bootstrap选项卡中点击href链接?
卓越飞翔博客
上一篇: 如何在 C# 中将输入读取为整数?
下一篇: C# 中的命令行参数
留言与评论(共有 0 条评论)
   
验证码:
隐藏边栏