python3 selenium copy即用

python3 selenium 入门级常用指令

wd.implicitly_wait(10) 如果没有找到元素,等待指定时间。如果是省市联动那种下拉框 要注意sleep,因为框框里面是有东西的

element = wd.find_element_by_id(“input1”)

element.clear() # 清除输入框已有的字符串
element.send_keys(‘白月黑羽’) # 输入新字符串

get_attribute(‘href’) 获取元素的属性值
element.get_attribute(‘outerHTML’) 获取整个元素对应的HTML
element.get_attribute(‘innerHTML’) 获取某个元素 内部 的HTML文本内容,
element.get_attribute(‘value’) 获取输入框里面的文字
element.get_attribute(‘innerText’) element.get_attribute(‘innerText’) 获取没有展示在界面的内容

打开 开发者工具,在 Elements 按Ctrl+F可以使用 XPath 格式进行验证
[] 根据属性查找
driver.findElement(By.xpath("//span[contains(text(),‘hello’)]")) 包含匹配
driver.findElement(By.xpath("//span[text()=‘新闻’]")) 绝对匹配
:nth-child(2) 第二个子元素
:nth-last-child(2) 倒数第二个子元素
~ 之后
https://www.runoob.com/cssref/css-selectors.html CSS 选择器

driver.switch_to.frame(driver.find_element_by_css_selector(‘iframe[src=“iframe1.html”]’)) 切换到iframe1.html
driver.switch_to_default_content() 切换到默认的 窗口

current_window = wd.current_window_handle # current_window变量保存当前窗口的句柄
wd.switch_to.window(mainWindow) #通过前面保存的老窗口的句柄,自己切换到老窗口

单选
#获取当前选中的元素
element = wd.find_element_by_css_selector(’#radioId input[checked=checked]’)
print('当前选中的是: ’ + element.get_attribute(‘value’))

#点选 指定属性
wd.find_element_by_css_selector(’#radioId input[value=“属性”]’).click()

checkbox框
#先把 已经选中的选项全部点击一下
elements = wd.find_elements_by_css_selector(’#checkboxId input[checked=“checked”]’)

#选择所有
for element in elements:
element.click()

#再点击 对应按钮
wd.find_element_by_css_selector("#checkboxId input[value=‘对应按钮名称’]").click()

Select多选框
#导入Select类
from selenium.webdriver.support.ui import Select

#创建Select对象
select = Select(wd.find_element_by_id(“ss_single”))

#通过 Select 对象选中小雷老师
select.select_by_visible_text(“aaa”)
select.select_by_visible_text(“bbb”)

冻结界面(定时 debugger )
setTimeout(function(){debugger}, 5000)

弹框处理
driver.switch_to.alert.accept() #确定
driver.switch_to.alert.dismiss() #确定
print(driver.switch_to.alert.text)# 打印 弹出框 提示信息

窗口大小
driver.get_window_size()#获取窗口大小
driver.set_window_size(x, y)#改变窗口大小
driver.title#获取当前窗口标题
driver.current_url
#获取当前窗口URL地址

截屏
driver.get_screenshot_as_file(‘1.png’) # 截屏保存为图片文件

以手机模式打开chrome浏览器
from selenium import webdriver
mobile_emulation = { “deviceName”: “Nexus 5” }
chrome_options = webdriver.ChromeOptions()
chrome_options.add_experimental_option(“mobileEmulation”, mobile_emulation)
driver = webdriver.Chrome( desired_capabilities = chrome_options.to_capabilities())
driver.get(‘http://www.baidu.com’)

上传文件
ele = wd.find_element_by_css_selector(‘input[type=file]’)# 先定位到上传文件的 input 元素
ele.send_keys(r’h:\g02.png’) # 再调用 WebElement 对象的 send_keys 方法

如果需要上传多个文件,可以多次调用send_keys
ele = wd.find_element_by_css_selector(‘input[type=file]’)
ele.send_keys(r’h:\g01.png’)
ele.send_keys(r’h:\g02.png’)

XPath wb.find_elements_by_xpath("//[@id=‘west’]")
或者的话 用逗号隔开 (option , h4)(//option | //h4)
并且是连续写即可 //div/p[2]
//
[@属性名=‘属性值’] 根据id属性选择 //[@id=‘west’]
//select[@class=‘single_choice’] 选择所有 select 元素中 class为 single_choice 的元素,class 要写全
//
[contains(@style,‘color’)] style属性值 包含 color 字符串的 页面元素
//[starts-with(@style,‘color’)] style属性值 以 color 字符串 开头 的 页面元素
//
[ends-with(@style,‘color’)] style属性值 以 某个 字符串 结尾 的 页面元素
//div/p[2] 选取父元素为div 中的 p类型 第2个 子元素
//div/[2] 选择父元素为div的第2个子元素,不管是什么类型
//p[last()-1] 选取p类型倒数最后一个元素前面一个元素,就是倒数第二个元素
//option[position()<=2] 选取option类型第1到2个子元素
//
[@class=‘single_choice’] | //[@class=‘multi_choice’] 选所有的 class 为 single_choice 或者 class 为 multi_choice 的元素
//
[@id=‘china’]/…/…/… 选择父节点/…
//[@class=‘single_choice’]/preceding-sibling:: 选择 class 为 single_choice 的元素的所有前面的兄弟节点
//*[@class=‘single_choice’]/following-sibling::div 选择 class 为 single_choice 的元素后续节点中的div节点

模版:

 from selenium import webdriver
import time

def set_driver(chrome_driver_path='C:\Program Files (x86)\Google\Chrome\Application\chromedriver.exe',headless=False):
    chrome_options = webdriver.ChromeOptions()
    prefs = {"": ""}
    prefs["credentials_enable_service"] = False
    prefs["profile.password_manager_enabled"] = False
    if headless==True:
        chrome_options.add_argument('--headless')
    chrome_options.add_experimental_option("prefs", prefs)  ##关掉密码弹窗
    chrome_options.add_argument('--disable-gpu')  # 谷歌文档提到需要加上这个属性来规避bug
    chrome_options.add_argument('lang=zh_CN.UTF-8')  # 设置默认编码为utf-8
    chrome_options.add_experimental_option('useAutomationExtension', False)  # 取消chrome受自动控制提示
    chrome_options.add_experimental_option("excludeSwitches", ['enable-automation'])  # 取消chrome受自动控制提示
    driver = webdriver.Chrome(options=chrome_options,executable_path=chrome_driver_path)
    driver.implicitly_wait(20)#隐式 等待10秒
    return driver

'''
打开百度 查看超链接
'''
def openBaidu():
    driver=set_driver(headless=False)
    driver.get("https://www.baidu.com/")
    driver.find_element_by_xpath('//*[@id="kw"]').send_keys("selenium")
    driver.find_element_by_xpath('//*[@id="su"]').click()

    for i in range (1,120):
        try:
            all_href = driver.find_element_by_xpath('//*[@id="' + str(i) + '"]')
            a = all_href.find_element_by_tag_name('a')
            print(str(i),a.text + "\t" + a.get_attribute('href'))
            if (i % 10 == 0):
                driver.find_element_by_xpath('//*[@id="page"]').find_element_by_xpath("//a[contains(text(),'下一页')]").click()
        except Exception as e:
            print(e)
            continue
'''
打开百度 
测试窗口句柄
'''
def openBaiduWindow():
    driver=set_driver()
    driver.get("https://www.baidu.com/s?ie=utf-8&f=8&rsv_bp=1&rsv_idx=1&tn=baidu&wd=selenium&fenlei=256&rsv_pq=932ba4020000d129&rsv_t=3c9cJgKGiChNGSTfSW1tqOV0O5q1pdYm1TVnfjYncDFRWrE1NXY4BrtHceU&rqlang=cn&rsv_enter=0&rsv_dl=tb&rsv_sug3=8&rsv_btype=i&inputT=195&rsv_sug4=195")
    current_window=driver.current_window_handle#获取当前窗口句柄
    driver.find_element_by_xpath("//*[contains(text(),'简书')]").click()
    time.sleep(2)
    all_window=driver.window_handles#获取当前窗口句柄
    driver.fullscreen_window()
    time.sleep(5)
    print('我要切换回去了 百度句柄了')
    driver.switch_to.window(current_window)#切换到开始保存的窗口的句柄
    print("切换后的窗口",driver.title)
    time.sleep(5)
    print('我要切换回去了 简书句柄')
    driver.switch_to.window(all_window[1])
    print("切换后的窗口",driver.title)
    time.sleep(10)


if __name__ == '__main__':
    openBaiduWindow()

建议:

如果需要进行定期自动化测试,可以自己写一个玩玩
如果没用过 就看教程,如果用过 直接copy 指令即可

参考 ;
Python + Selenium Web自动化 https://www.bilibili.com/video/BV1Z4411o7TA?p=34
上面b站教程 对应文档 http://www.python3.vip/tut/auto/selenium/01/

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章