python-selenium自动化基础

一、Python与selenium环境搭建 

①下载python:https://www.python.org/
②安装python并配置环境变量:D:Python34
③下载pip:https://pypi.python.org/pypi/pip
④cmd进入到pip解压路径运行:python setup.py install
⑤配置pip环境变量:D:Python34Scripts
⑥cmd进入到pip解压路径运行:pip install -U selenium #安装pip

二、使用selenium的webdirver模块对浏览器进行操作 

注意:需要安装浏览器版本对应的driver驱动

from selenium import webdriver  # 导入webdriver

driver = webdriver.Chrome()  # 实例化Chrome浏览器
driver.get("http://www.baidu.com")  # 打开http://www.baidu.com
print(driver.title)  # 打印title
print(driver.current_url)  # 打印 url
# 根据id获取元素
ele = driver.find_element_by_id("kw")
ele.clear()  # 清除元素文本
ele.send_keys("lily")  # 写入lily

二、webdriver模块对浏览器进行操作:元素的定位 

b.find_element_by_link_text(arg) #根据标签文本获取元素
b.find_element_by_partial_link_text(arg) #根据标签文本模糊查询获取元素
b.find_element_by_css_selector() #根据css路径获取元素
xpath定位元素:/ // . .. @id count() loval-name()
b.find_element_by_xpath('/html/body/form/input') #form元素下的所有input
b.find_element_by_xpath('/html/body/form/input[1]') #根据下标定位某一个input

二、鼠标和键盘模拟用户行为 

①导入 ActionChains:from selenium.webdriver.common.action_chains import ActionChains
②用于生成模拟用户行为:ActionChains(driver)
③执行存储行为:perform()

ele=driver.find_element_by_link_text(arg)
ActionChains(driver).move_to_element(ele).perform()

二、多窗口切换 

d.window_handles #所有打开的窗口
d.switch_to_window(d.window_handles[1]) #根据下标定位窗口
原文地址:https://www.cnblogs.com/lilyo/p/11975601.html