※This article is based on Python 3.7.3
推荐使用Edge浏览器,因为Chrome的版本问题,webdrive总是没有最新的
浏览器下载地址:
https://www.microsoft.com/zh-cn/edge
驱动器下载地址:
https://developer.microsoft.com/zh-cn/microsoft-edge/tools/webdriver
浏览器下载地址:
http://www.firefox.com.cn
驱动器下载地址:
https://github.com/mozilla/geckodriver/releases
浏览器下载地址:
https://www.google.cn/chrome
驱动器下载地址:
http://chromedriver.storage.googleapis.com/index.html
下载路径
http://npm.taobao.org/mirrors/chromedriver/
要和本地的Chrome的版本一致,否则报错
selenium.common.exceptions.WebDriverException: Message: unknown error: cannot connect to chrome at 127.0.0.1:9527 from session not created: This version of ChromeDriver only supports Chrome version 99 Current browser version is 116.0.5845.142 Stacktrace: Backtrace: Ordinal0 [0x007B9943+2595139] Ordinal0 [0x0074C9F1+2148849] Ordinal0 [0x00644528+1066280] Ordinal0 [0x006642C3+1196739] Ordinal0 [0x0065D83B+1169467] Ordinal0 [0x0065D606+1168902] Ordinal0 [0x00690530+1377584]
WebDriverWait(driver,timeout=10).until(ec.presence_of_element_located(locator))
超时时间内定位到locator后执行下一步,否则超时异常
driver.implicitly_wait(timeout=10)
等待页面完全加载好才能执行下一步,只需要获取某个元素时,有点浪费时间,配一个限制一下避免部分页面加载慢
time.sleep(10)
不要用这种,不稳定
driver.set_page_load_timeout(timeout=20)
执行get(url)方法,页面等待超时时间
Html Code
<input type="text" class="s_ipt" name="wd" id="kw" />
find_element_by_id(id) #id参数表示的是id的属性值;(定位的元素必须有ID属性)
driver.find_element_by_id("kw")
find_element_by_name(name) #name参数表示的是name的属性值;(定位元素必须有NAME属性)
driver.find_element_by_name("wd")
find_element_by_class_name(class_name) #class_name参数表示的是class的属性值;(定位元素必须有class属性)
driver.find_element_by_class_name("s_ipt")
注意:class属性值有多个时(用空格隔开),仅需要其中一个属性值:(但若是使用Xpath属性定位时,需要用到全部属性值)
find_element_by_tag_name(tag_name) #tag_name参数表示的是元素的标签名;(定位元素必须有标签名)如果有重复的元素定位到的元素默认都是第一个;
driver.find_element_by_tag_name("input")
定位方法:find_element_by_xpath(xpath) #xpath表达式
绝对路径:表达式以/html开头,元素的层级之间是以/分隔,相同层级的元素可以使用下标,下标从1开始;需要列出元素所经过的所有层级元素,在工作中,一般不使用绝对路径。
/html/body/div/div/div/div/div
路径定位 定位方法:find_element_by_xpath(xpath) #xpath表达式
相对路径:匹配任意层级的元素,是以//tag_name或者//*开头,也可以使用下标,下标从1 开始。
//div[10]//button
<input type="text" class="s_ipt" name="wd" id="kw" /> driver.find_element_by_xpath(//input[@id='kw'])
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.common.exceptions import TimeoutException, NoSuchElementException
from selenium import webdriver
from selenium.webdriver.edge.service import Service
from selenium.webdriver.common.keys import Keys
import time
class SeleniumHelper:
def __init__(self, driver):
self.driver = driver
def find_element(self, locator, timeout=10):
"""
查找单个元素
:param locator: 元素定位信息,如(By.ID, 'element_id')
:param timeout: 超时时间,默认为10秒
:return: WebElement对象或None
"""
try:
element = WebDriverWait(self.driver, timeout).until(
EC.presence_of_element_located(locator)
)
return element
except (TimeoutException, NoSuchElementException):
return None
def find_elements(self, locator, timeout=10):
"""
查找多个元素
:param locator: 元素定位信息,如(By.CLASS_NAME, 'element_class')
:param timeout: 超时时间,默认为10秒
:return: WebElement对象列表或空列表
"""
try:
elements = WebDriverWait(self.driver, timeout).until(
EC.presence_of_all_elements_located(locator)
)
return elements
except (TimeoutException, NoSuchElementException):
return []
# Edge浏览器 https://developer.microsoft.com/en-us/microsoft-edge/tools/webdriver/
s=Service('F:\Temp\edgedriver_win64\msedgedriver.exe')
options = webdriver.EdgeOptions()
options.use_chromium = True
# 屏蔽inforbar
options.add_experimental_option('useAutomationExtension', False)
options.add_experimental_option('excludeSwitches', ['enable-automation', 'enable-logging'])
options.add_argument("start-maximized")
# options.add_argument('--headless')
options.binary_location=r'C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe'
driver = webdriver.Edge(service=s, options=options)
driver.get('https://www.baidu.com')
# 创建SeleniumHelper对象
helper = SeleniumHelper(driver)
search_box = helper.find_element((By.ID, 'kw'))
if search_box:
search_box.send_keys("aaaaaa")
search_box.send_keys(Keys.RETURN)
time.sleep(6)
#driver.quit()
ERROR: Could not find a version that satisfies the requirement win32api (from versions: none) ERROR: No matching distribution found for win32api
使用pip install pypiwin32 安装成功
E:\python>pip install pypiwin32
XXX
コメント: