#!/usr/bin/env python
# -*- coding:utf-8 -*-
from selenium.webdriver.support.wait import WebDriverWait
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
# 配置对象
options = webdriver.ChromeOptions()
# 隐藏“Chrome正受到自动测试软件的控制。”
options.add_experimental_option('excludeSwitches', ['enable-automation'])
def waitxpath(driver, xpath):
try:
# 显示等待10s,每秒判断元素是否加载完成
WebDriverWait(driver, 10, 1).until(
lambda x: x.find_element(By.XPATH, value=xpath)
)
except Exception as e:
raise e
# chromedriver是当前路径,已经下载好的chromeweb驱动。
chromedriver = 'chromedriver'
driver = webdriver.Chrome(executable_path=chromedriver, options=options)
driver.get('https://www.baidu.com/')
# 搜索框元素对应的XPath,与XPath语法相关的内容
# 在浏览器开发者工具模式下,可以直接通过找到你想要操作的元素,然后选择复制--> XPath。
search_input_xpath = '//*[@id="kw"]'
# 显式等待
waitxpath(driver, search_input_xpath)
# 通过XPath定位元素
search_input = driver.find_element(By.XPATH, value=search_input_xpath)
search_input.send_keys('python')
search_input.send_keys(Keys.ENTER)
浏览器自动化 - 等待XPath元素加载
于 2022-09-28 09:43:45 首次发布