在我们开始之前,只需确保您已安装以下软件:
pip install selenium
使用 Selenium 打开链接的最简单方法是使用 WebDriver 对象的 get() 方法。此方法指示浏览器导航到指定的 URL。
driver.get(url)
参数:
from selenium import webdriver # initialize the web driver driver = webdriver.Firefox() # Open the tutorials point website using get() method driver.get("https://www.tutorialspoint.com")
假设您在网页中嵌入了一些链接,例如按钮、图像和链接。在这种情况下,我们不能直接使用 get() 方法来打开这些链接。我们需要使用硒找到元素,然后执行单击操作以打开链接。
find_element():find_element() 用于在网页中定位元素,find_element() 可以与 Id、类和 xpath 一起使用。
driver.find_element(By.XPATH, "xpath")
click(): the click() method is used to perform a click operation on an HTML element.
element.click()
from selenium import webdriver from selenium.webdriver.common.by import By # initialize the web driver driver = webdriver.Firefox() # Open the tutorials point website using get() method driver.get("https://www.tutorialspoint.com/index.htm") # clicking the courses tab in homepage. driver.find_element(By.XPATH,"/html/body/header/nav/div/div[1]/ul[2]/li[2]/a").click()
现在让我们讨论如何在新选项卡或新窗口中打开链接。当我们想要使用多个选项卡时,这可能非常方便。
execute_script()
execute_script(script)
from selenium import webdriver from selenium.webdriver.common.by import By # initialize the web driver driver = webdriver.Firefox() # Open a new tab driver.execute_script("window.open();") # Switch to the newly opened tab driver.switch_to.window(driver.window_handles[1]) # Open the tutorials point website using get() method driver.get("https://www.tutorialspoint.com")
在本文中,我们学习了在 Python 中使用 Selenium 打开链接的多种方法。包括直接使用 get() 方法打开链接、单击包含链接的元素或在新选项卡/窗口中打开链接。根据您的使用案例,您可以选择最适合您的方法。