1、打开网页
from selenium import webdriver from selenium.webdriver.chrome.service import Service # 浏览器驱动路径,注意驱动与selenium版本相匹配 service = Service(executable_path=r'D:\chromedriver.exe') options = webdriver.ChromeOptions() driver = webdriver.Chrome(service=service, options=options) driver.get("https://www.baidu.com/") # 浏览器窗口最大化 driver.maximize_window()
2、通过Xpath查找网页元素
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
xpath = '//div[text()="登录"]'
# 常规方法,需要在元素显示完成后才能找到,否则会报错,通常前面加上time.sleep(2)设置等待时间
element = driver.find.element(By.XPATH, xpath)
# 程序自动等待元素加载
element = WebDriverWait(driver, 10).until(EC.presence_of_element_located(By.XPATH, xpath))
!注:xpath常用表达方式
通过文字精准查找://button[text()="登录"]
通过文字模糊查找://button[contains("登录")]
通过组件属性值查找://button[@id="button"]
确定属性的值,但属性名称动态变化://span[.="button"]
xpath层级关系表示://不限层级的下级 /表示直接下级 \..表示直接上级
如何快速定位元素的xpath:F12-Elements,小箭头点击页面元素可快速定位到HTML源码,右键“Copy XPath”
对于鼠标悬停才会出现的元素:直接在页面右击,选择“检查”,即可定位到HTML源码
如何检验xpath是否正确:浏览器打开想要查找的页面,F12-Console,$x('//button[contains("登录")]'),回车即可查看页面中是否可以通过xpath查找到对应元素
3、操作页面元素
点击:element.click()
传值:element.send_keys('username')
特殊情况处理
- 当按钮上面存在蒙层时,click()操作不生效,这时可使用script方法模拟鼠标点击:driver.execute_script("arguments[0].click()", element)
- 元素被隐藏,click()操作不生效:
driver.execute_script("arguments[0].style.display = 'block';", element)
driver.execute_script("arguments[0].click()", element)