Selenium positioning web page elements and window switching

1. Locating individual web page elements

1.1 Locating web page elements by id
import time
from selenium import webdriver
from selenium.webdriver import Keys
from selenium.webdriver.common.by import By

driver = webdriver.Chrome() # 打开 chrome 浏览器
driver.get("https://www.baidu.com/")

input = driver.find_element(By.ID,"kw")
input.send_keys('大数据就业前景')
input.send_keys(Keys.ENTER)
time.sleep(10)
driver.quit()

1.2 Locate a single web page element by path

1) Obtaining method of web page object path

2) Code example

import time
from selenium import webdriver
from selenium.webdriver import Keys
from selenium.webdriver.common.by import By

driver = webdriver.Chrome() # 打开 chrome 浏览器
driver.get("https://www.baidu.com/")

input = driver.find_element("xpath","/html/body/div[1]/div[1]/div[5]/div/div/form/span[1]/input")
# 指定搜索栏中的内容
input.send_keys("大数据就业前景")
# 相当于回车键
input.send_keys(Keys.ENTER)
# 设置网页停留时间
time.sleep(30)
driver.quit()

 2. Window switching

        When Selenium takes control of a web browser, new windows often pop up. If you need to target the new window's meta
element, the element cannot be located without switching, so you need to switch to a new window before locating the element.
#获取当前浏览器的所有窗口句柄
handles = driver.window_handles
#切换到最新打开的窗口
driver.switch_to.window(handles[-1])
#切换到倒数第二个打开的窗口
driver.switch_to.window(handles[-2])
#切换到最开始打开的窗口
driver.switch_to.window(handles[0])

Guess you like

Origin blog.csdn.net/m0_64562972/article/details/130315517