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/

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