WEB自動化詳解

參考鏈接:

web自動化測試教案:http://www.cnblogs.com/zidonghua/p/7430083.html

(IFRAME是HTML標簽宙枷,作用是文檔中的文檔赤兴,或者浮動的框架(FRAME)

1.操作元素基本方法:

? #coding:utf-8

? from selenium import webdriver? ? #將selenium導(dǎo)入到webdriver模塊

? driver=webdriver.Firefox()? ? ? ? #定義驅(qū)動為Firefox瀏覽器

(1)打開就用get函數(shù):

? ? driver.get("https://www.baidu.com ")? ? ? ? ? ? ? ? #打開百度瀏覽器

(2)設(shè)置等待時間就用sleep函數(shù):

? ? time.sleep(3)? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? #等待3秒

(3) 頁面刷新就用refresh函數(shù):? ? ? ? ? ?

? ? driver.refresh()? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? #刷新頁面

(4) 頁面切換:

? ? ? driver.back()? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? #返回上一頁譬胎。

? ? ? driver.forward()? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? #切換到下一頁

(5)設(shè)置窗口大辛晟病:

? ? ? driver.set_window_size(540,960)? ? ? ? ? ? ? ? ? ? #設(shè)置窗口大小為540*960分辨率

? ? ? driver.maximize_window()? ? ? ? ? ? ? ? ? ? ? ? ? ? #設(shè)置窗口最大化?

(6)截屏后設(shè)置存放路徑:

? ? ? driver.get_screenshot_as_file(“D:\\test\\b1.jpg”) #截屏后將b1.jpg文件存放到D盤test文件夾中

(7)退出:

? ? ? driver.close()? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? #關(guān)閉當前窗口

? ? ? driver.quit()? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? #結(jié)束進程

2.操作元素(鍵盤和鼠標事件):

? ? (1) 鼠標操作:?

? ? ? ? 點擊:click()

? ? ? ? 清空輸入框:clear()

? ? ? ? 輸入字符串:send_keys(),如果要發(fā)送中文逆甜,則字符串前要加u圆丹,

? ? ? ? ? ? ? ? ? ? 比如send_keys(u"你好哦")

? ? ? ? 提交表單:submit()

? ? (2)鼠標懸停事件:

? ? ? ? ? from selenium.webdriver.common.action_chainsimport ActionChains? ? #導(dǎo)入包

? ? ? ? ? perform()? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? #用于執(zhí)行所有ActionChains中的行為.

? ? ? ? ? move_to_element()? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? #鼠標懸停

? ? (3)鼠標其他事件:

? ? ? ? ? 右擊:context_click()

? ? ? ? ? 雙擊:double_click()

? ? (2)鍵盤操作:在模擬鍵盤操作前先要導(dǎo)入鍵盤模塊:

? ? ? ? ? ? ? ? ? from selenium.webdriver.common.keys import Keys

? ? ? ? send_keys(Keys.ENTER)? ? ? ? ? ? # 模擬回車鍵

? ? ? ? send_keys(Keys.CONTROL,'c')? ? ? # 模擬ctrl+c

? ? ? ? send_keys(Keys.CONTROL,'v')? ? ? # 模擬ctrl+v

? ? ? ? send_keys(Keys.CONTROL,'a')? ? ? # 模擬ctrl+a

? ? ? ? send_keys(Keys.CONTROL,'x')? ? ? # 模擬ctrl+x

? ? ? ? send_keys(Keys.TAB)? ? ? ? ? ? ? # 模擬制表鍵TAB

3.? handle(句柄)就相當于C中的函數(shù)指針,

? ? 元素有屬性李请,瀏覽器的窗口其實也有屬性的,只是你看不到厉熟,瀏覽器窗口的屬性用句柄(handle)來識別导盅。

? ? 獲取當前頁面的句柄:driver.current_window_handle

? ? 切換窗口:driver.switch_to.windows()

4.定位一組元素elements的步驟:

? (1)用firebug查看頁面元素,查看所輸入關(guān)鍵字的搜索結(jié)果的共同屬性:

? ? <例>#coding:utf-8

? ? ? ? from selenium import webdriver

? ? ? ? driver=webdriver.Firefox()

? ? ? ? driver.get("https://www.baidu.com")

? ? ? ? driver.implicitly_wait(10)

? ? ? ? driver.find_element_by_id("kw").send_keys(u"測試部落")

? ? ? ? driver.find_element_by_id("kw").submit()

? ? ? ? s=driver.find_element_by_css_selector("h3.t>a")? ? ? ? #定位一組元素?

? (2)確認定位結(jié)果揍瑟,可以通過attribute來獲取href屬性白翻,并且打印出url地址:

? ? ? for i in s:

? ? ? ? print i.get_attribute("href")

5.隨機函數(shù):

(1)隨機打印一個數(shù),在此之前绢片,需要先導(dǎo)入隨機函數(shù):import random.

? ? <例>import random

? ? ? ? t=random.randint(0,9)

? ? ? ? print(t)

? (2)隨機打開url:

? ? ? 從返回結(jié)果中隨機取一個url地址滤馍,通過get方法打開url。

? ? ? <例>#coding:utf-8

? ? ? ? from selenium import webdriver

? ? ? ? import random

? ? ? ? driver=webdriver.Firefox()

? ? ? ? driver.get("https://www.baidu.com")

? ? ? ? driver.implicitly_wait(10)

? ? ? ? driver.find_element_by_id("kw").send_keys(u"測試部落")

? ? ? ? driver.find_element_by_id("kw").submit()

? ? ? ? s=driver.find_element_by_css_selector("h3.t>a")? ? ? ? #定位一組元素?

? ? ? ? t=random.randint(0,9)? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? #設(shè)置隨機值

? ? ? ? a=s[t].get_attribute("href")? ? ? ? ? ? ? ? ? ? ? ? ? ? #隨機取一個結(jié)果獲取url地址

? ? ? ? print a

? ? ? ? driver.get(a)

6.iframe:

? Frame與Iframe兩者可以實現(xiàn)的功能基本相同底循,不過Iframe比Frame具有更多的靈活性巢株。 frame是整個頁面的框架,iframe是內(nèi)嵌的網(wǎng)頁元素熙涤,也可以說是內(nèi)嵌的框? ? 架阁苞,Iframe標記又叫浮動幀標記困檩,可以用它將一個HTML文檔嵌入在一個HTML中顯示。

? (1)如果要切換iframe,可以使用switch_to_frame方法實現(xiàn)那槽;

? ? ? <例>#coding:utf-8

? ? ? from selenium import webdriver

? ? ? driver=webdriver.Firefox()

? ? ? driver.get("http:mail.163.com/")

? ? ? driver.implicitly_wait(10)

? ? ? driver.switch_to_frame("x-URS-iframe")

? ? ? driver.find_element_by_name("email").send_keys("123")

? ? ? driver.find_element_by_name("password").send_key("456")?

? (2)如果iframe沒有id怎么辦悼沿?

? ? iframe的切換是默認支持id和name方法的,當然實際情況中會遇到?jīng)]有id屬性和name屬性為空的情況骚灸,這時候就需要先定位iframe元素對象,這里我可以通過tag? ? ? 先定位到糟趾,也能達到同樣效果.

? ? ? <例>#coding:utf-8

? ? ? from selenium import webdriver

? ? ? driver=webdriver.Firefox()

? ? ? driver.get("http:mail.163.com/")

? ? ? driver.implicitly_wait(10)

? ? ? driver.switch_to_frame("x-URS-iframe")

? ? ? driver.find_element_by_name("email").send_keys("123")

? ? ? driver.find_element_by_name("password").send_key("456")?

? ? (3)釋放iframe:如果想要返回到主頁面可以用switch_to_default_content()方法回到主頁面。

? ? ? ? <例>#coding:utf-8

? ? ? from selenium import webdriver

? ? ? driver=webdriver.Firefox()

? ? ? driver.get("http:mail.163.com/")

? ? ? driver.implicitly_wait(10)

? ? ? driver.switch_to_frame("x-URS-iframe")

? ? ? driver.find_element_by_name("email").send_keys("123")

? ? ? driver.find_element_by_name("password").send_key("456")?

? ? ? driver.switch_to.default_content()? ? ? ? ? ? ? #釋放iframe,重新回到主頁面逢唤。

7.select下拉框的定位:

? (1)二次定位方式:即先定位select框拉讯,再定位select里的選項涤浇;

? ? <例> #coding:utf-8

? ? ? ? ? from selenium import webdriver

? ? ? ? ? from selenium.webdriver.common.action_chains import ActionChains

? ? ? ? ? driver=webdriver.Firefox()

? ? ? ? ? url="https://www.baidu.com"

? ? ? ? ? driver.get(url)

? ? ? ? ? driver.implicitly_wait(10)

? ? ? ? #鼠標移動到“設(shè)置”按鈕

? ? ? ? ? mouse=driver.find_element_by_link_text("設(shè)置")

? ? ? ? ? ActionChains(driver).move_to_element(mouse).perform()

? ? ? ? ? driver.find_element_by_link_text("搜索設(shè)置").click()

? ? ? ? #分兩步:先定位下拉框鳖藕,再點擊選項

? ? ? ? ? s=driver.find_element_by_id("nr")

? ? ? ? ? s.find_element_by_xpath("http://option[@value='50']").click()

? ? ? ? (最后一步的另外寫法:

? ? ? ? ? driver.find_element_by_id("nr").find_element_by_xpath("http://option[@value='50']").click()

? ? ? ? ? )

? (2)直接定位:就是要展開CSS樣式表的層級結(jié)構(gòu),然后自己寫xpath或者css只锭,一次性直接定位到option上的內(nèi)容即可著恩。

8.select模塊定位:

? (1)導(dǎo)入Select模塊,直接根據(jù)屬性或索引定位index。

? ? 首先要導(dǎo)入select方法:from selenium.webdriver.support.select import Select? ? ?

? ? 然后通過select選項的索引來定位選擇對應(yīng)選項(從0開始計數(shù))蜻展,如選擇第三個選項:select_by_index(2)

? ? <例> #coding:utf-8

? ? ? ? ? from selenium import webdriver

? ? ? ? ? from selenium.webdriver.common.action_chains import ActionChains

? ? ? ? ? from selenium.webdriver.support.select import select

? ? ? ? ? driver=webdriver.Firefox()

? ? ? ? ? url="https://www.baidu.com"

? ? ? ? ? driver.get(url)

? ? ? ? ? driver.implicitly_wait(10)

? ? ? ? #鼠標移動到“設(shè)置”按鈕

? ? ? ? ? mouse=driver.find_element_by_link_text("設(shè)置")

? ? ? ? ? ActionChains(driver).move_to_element(mouse).perform()

? ? ? ? ? driver.find_element_by_link_text("搜索設(shè)置").click()

? ? ? ? ? #通過索引:select_by_index()

? ? ? ? ? s=driver.find_element_by_id("nr")

? ? ? ? ? select(s).select_by_index(2)? ? ? ? ? ? ? #通過index來定位喉誊,每頁顯示2條

? ? (2)通過選項的value值來定位:

? ? ? ? ? <例> #coding:utf-8

? ? ? ? ? from selenium import webdriver

? ? ? ? ? from selenium.webdriver.common.action_chains import ActionChains

? ? ? ? ? from selenium.webdriver.support.select import select

? ? ? ? ? driver=webdriver.Firefox()

? ? ? ? ? url="https://www.baidu.com"

? ? ? ? ? driver.get(url)

? ? ? ? ? driver.implicitly_wait(10)

? ? ? ? #鼠標移動到“設(shè)置”按鈕

? ? ? ? ? mouse=driver.find_element_by_link_text("設(shè)置")

? ? ? ? ? ActionChains(driver).move_to_element(mouse).perform()

? ? ? ? ? driver.find_element_by_link_text("搜索設(shè)置").click()

? ? ? ? ? #通過索引:select_by_value()

? ? ? ? ? s=driver.find_element_by_id("nx")

? ? ? ? ? select(s).select_by_value("20")? ? ? ? ? ? ? ? ? #通過value來定位,每頁顯示20條

? ? ? (3)通過選項的文本內(nèi)容來定位:

? ? ? ? ? <例> #coding:utf-8

? ? ? ? ? from selenium import webdriver

? ? ? ? ? from selenium.webdriver.common.action_chains import ActionChains

? ? ? ? ? from selenium.webdriver.support.select import select

? ? ? ? ? driver=webdriver.Firefox()

? ? ? ? ? url="https://www.baidu.com"

? ? ? ? ? driver.get(url)

? ? ? ? ? driver.implicitly_wait(10)

? ? ? ? #鼠標移動到“設(shè)置”按鈕

? ? ? ? ? mouse=driver.find_element_by_link_text("設(shè)置")

? ? ? ? ? ActionChains(driver).move_to_element(mouse).perform()

? ? ? ? ? driver.find_element_by_link_text("搜索設(shè)置").click()

? ? ? ? ? #通過索引:select_by_value()

? ? ? ? ? s=driver.find_element_by_id("nx")

? ? ? ? ? select(s).select_by_visible_text("每頁顯示50條")? ? ? ? ? ? ? ? ? #通過text來定位纵顾,每頁顯示50條

? ? ? (4)select模塊其它方法:

? ? ? ? ? deselect_all()? ? ? ? ? :取消所有選項

? ? ? ? ? deselect_by_index()? ? :取消對應(yīng)index選項

? ? ? ? ? deselect_by_value()? ? ? :取消對應(yīng)value選項

? ? ? ? ? deselect_by_visible_text() :取消對應(yīng)文本選項

? ? ? ? ? first_selected_option()? :返回第一個選項

? ? ? ? ? all_selected_options()? :返回所有的選項

9.alert\confirm\prompt:

? 不是所有的彈出框都叫alert伍茄,在使用alert方法前,先要識別出到底是不是alert施逾。

? alert\confirm\prompt彈出框操作主要方法有:

? text:獲取文本值

? accept() :點擊"確認"

? dismiss() :點擊"取消"或者叉掉對話框

? send_keys() :輸入文本值 --僅限于prompt,在alert和confirm上沒有輸入框

? (1)關(guān)于alert的操作:

? ? ? 1.先用switch_to_alert()方法切換到alert彈出框上

? ? ? 2.可以用text方法獲取彈出的文本 信息

? ? ? 3.accept()點擊確認按鈕

? ? ? 4.dismiss()相當于點右上角x敷矫,取消彈出框(url的路徑,直接復(fù)制瀏覽器打開的路徑)

? ? ? <例> #coding:utf-8

? ? ? ? ? from selenium import webdriver

? ? ? ? ? import time

? ? ? ? ? url="file://c:/users/admin/Desktop/testalert.html"

? ? ? ? ? driver=webdriver.Firefox()

? ? ? ? ? driver.get(url)

? ? ? ? ? time.sleep(4)

? ? ? ? ? driver.find_element_by_id("alert").click()

? ? ? ? ? time.sleep(3)

? ? ? ? ? t=driver.switch_to_alert()

? ? ? ? ? print t.text? ? ? ? ? #打印警告框文本內(nèi)容

? ? ? ? ? t.accept()? ? ? ? ? ? #點擊警告框的確認按鈕

? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? #t.dismiss()相當于點擊取消按鈕

? (2)關(guān)于confirm操作:

? ? ? 1.先用switch_to_alert()方法切換到alert彈出框上

? ? ? 2.可以用text方法獲取彈出的文本 信息

? ? ? 3.accept()點擊確認按鈕

? ? ? 4.dismiss()相當于點取消按鈕或點右上角x妇多,取消彈出框(url的路徑鲸郊,直接復(fù)制瀏覽器打開的路徑)

? ? ? <例> #coding:utf-8

? ? ? ? ? from selenium import webdriver

? ? ? ? ? import time

? ? ? ? ? url="file://c:/users/admin/Desktop/testalert.html"

? ? ? ? ? driver=webdriver.Firefox()

? ? ? ? ? driver.get(url)

? ? ? ? ? time.sleep(4)

? ? ? ? ? driver.find_element_by_id("confirm").click()

? ? ? ? ? time.sleep(3)

? ? ? ? ? t=driver.switch_to_alert()

? ? ? ? ? print t.text? ? ? ? ? #打印警告框文本內(nèi)容

? ? ? ? ? t.accept()? ? ? ? ? ? #點擊警告框的確認按鈕

? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? #t.dismiss()相當于點擊取消按鈕

? (3)關(guān)于prompt操作:

? ? ? 1.先用switch_to_alert()方法切換到alert彈出框上

? ? ? 2.可以用text方法獲取彈出的文本 信息

? ? ? 3.accept()點擊確認按鈕

? ? ? 4.dismiss()相當于點右上角x古今,取消彈出框

? ? ? 5.send_keys()這里多個輸入框,可以用send_keys()方法輸入文本內(nèi)容(url的路徑怎茫,直接復(fù)制瀏覽器打開的路徑)

? ? ? <例>coding:utf-8

? ? ? ? ? from selenium import webdriver

? ? ? ? ? import time

? ? ? ? ? url="file:///c:/users/admin/Desktop/testalert.html"

? ? ? ? ? driver=webdriver.Firefox()

? ? ? ? ? driver.get(url)

? ? ? ? ? time.sleep(5)

? ? ? ? ? driver.find_element_by_id("prompt").click()

? ? ? ? ? time.sleep(5)

? ? ? ? ? t=driver.switch_to_alert()

? ? ? ? ? #打印警告框文本內(nèi)容

? ? ? ? ? print t.text

? ? ? ? ? t.send_keys("hello selenium2")

? ? ? ? ? t.accept()? ? ? ? ? ? #點擊警告框的確認按鈕

? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? #t.dismiss()相當于點擊取消按鈕

10.select遇到的問題:

? ? 1.在操作百度設(shè)置里面,點擊“保存設(shè)置”按鈕時妓灌,alert彈出框沒有彈出來轨蛤。(Ie瀏覽器是可以的)

? ? 2.分析原因:經(jīng)過慢慢調(diào)試后發(fā)現(xiàn),在點擊"保存設(shè)置"按鈕時虫埂,由于前面的select操作后祥山,失去了焦點

? ? 3.解決辦法:在select操作后,做個click()點擊操作告丢。

11.單選框和復(fù)選框(radiobox枪蘑、checkbox)的定位:

? (1)全部勾選:

? ? ? 可以用到定位一組元素损谦,復(fù)選框的type=checkbox,這里可以用xpath語法:.//*[@type='checkbox'];

? ? ? find_elements是不能直接點擊的,它是復(fù)數(shù)的岳颇,所以只能先獲取到所有的checkbox對象照捡,然后通過for循環(huán)

? ? ? 去一個個點擊操作;

? ? ? <例> #coding:utf-8

? ? ? ? ? from selenium import webdriver

? ? ? ? ? import time

? ? ? ? ? driver=webdriver.Firefox()

? ? ? ? ? driver.get("file:///C:/Users/Gloria/Desktop/checkbox.html")

? ? ? ? ? checkboxs=driver.find_elements_by_xpath(".//*[@type='checkbox']")

? ? ? ? ? for i in checkboxs:

? ? ? ? ? ? ? ? i.click()

? ? (2)判斷是否選中:is_selected()

? ? ? <例> # coding:utf-8

? ? ? ? ? ? from selenium import webdriver

? ? ? ? ? ? import time

? ? ? ? ? ? driver=webdriver.Firefox()

? ? ? ? ? ? driver.get("file:///C:/Users/Gloria/Desktop/checkbox.html")

? ? ? ? ? ? #沒點擊操作前,判定選項框的狀態(tài)

? ? ? ? ? ? s=driver.find_element_by_id("boy").is_selected()

? ? ? ? ? ? print s

? ? ? ? ? ? driver.find_element_by_id("boy").click()

? ? ? ? ? ? #點擊后话侧,判斷元素是否為選中的狀態(tài)

? ? ? ? ? ? r=driver.find_element_by_id("boy").is_selected()

? ? ? ? ? ? print r

12.table表格定位:

? ? (1)table特征:

? ? ? ? 1.table頁面查看源碼一般有這幾個明顯的標簽:table栗精、tr、th瞻鹏、td

? ? ? ? 2.<table>標示一個表格

? ? ? ? 3.<tr>標示這個表格中間的一個行

? ? ? ? 4.</th> 定義表頭單元格

? ? ? ? 5.</td> 定義單元格標簽悲立,一組<td>標簽將將建立一個單元格,<td>標簽必須放在<tr>標簽內(nèi).

? ? ? (2)表格的元素定位可以用xpath定位方式新博,比如:.//*[@id='myTable']/tbody/tr[2]/td[1]

? ? ? ? 需要說明的是薪夕,這里定位的格式是固定的,只需改tr和td后面的數(shù)字就可以了.如第二行第一列tr[2]td[1].

? ? ? ? <例>from selenium import webdriver

? ? ? ? ? ? url='file:///C:/Users/Gloria/Desktop/table.html'

? ? ? ? ? ? driver=webdriver.Firefox()

? ? ? ? ? ? driver.get(url)

? ? ? ? ? ? t=driver.find_element_by_xpath(".//*[@id='myTable']/tbody/tr[2]/td[1]")

? ? ? ? ? ? print t.text

13.加載Firefox配置:

? (1)加載Chrome配置方法就是將username改成自己電腦的名字即可(不要用中文)

? <例>'--user-data-dir=C:\Users\username\AppData\Local\Google\Chrome\User Data'

? ? ? ? #coding:utf-8

? ? ? ? from selenium import webdriver

? ? ? ? #加載chrome配置

? ? ? ? option=webdriver.ChromeOptions()

? ? ? ? option.add_argument('--user-data-dir=C:\Users\Gloria\AppData\Local\Google\Chrome\User Data')

? ? ? ? driver = webdriver.Chrome(chrome_options=option)

? ? ? ? driver.implicitly_wait(30)

? ? ? ? driver.get("http://www.cnblogs.com/yoyoketang/")

? ? (2)wap測試:

? ? <例>#coding:utf-8

? ? ? ? from selenium import webdriver

? ? ? ? option=webdriver.ChromeOptions()

? ? ? ? #偽裝iphone登錄:

? ? ? ? option.add_argment('--user-agent=iphone')

? ? ? ? #偽裝android登錄:

? ? ? ? option.add-argment('--user-agent=android')

? ? ? ? driver=webdriver.Chrome(chrome_options=option)

? ? ? ? driver.get('http://www.taobao.com')

14.富文本(richtext):

? <例># coding:utf-8

? ? ? from selenium import webdriver

? ? ? from selenium.webdriver.common.keys import Keys

? ? ? import time

? ? ? profileDir = r'C:\Users\Gloria\AppData\Roaming\Mozilla\Firefox\Profiles\1x41j9of.default'

? ? ? profile = webdriver.FirefoxProfile(profileDir)

? ? ? driver = webdriver.Firefox(profile)

? ? ? bolgurl = "http://www.cnblogs.com/"

? ? ? yoyobolg = bolgurl + "yoyoketang"

? ? ? driver.get(yoyobolg)

? ? ? driver.find_element_by_id("blog_nav_newpost").click()

? ? ? time.sleep(5)

? ? ? edittile = u"Selenium2+python自動化23-富文本"

? ? ? editbody = u"這里是發(fā)帖的正文"

? ? ? driver.find_element_by_id("Editor_Edit_txbTitle").send_keys(edittile)

? ? ? driver.switch_to.frame("Editor_Edit_EditorBody_ifr")

? ? ? driver.find_element_by_id("tinymce").send_keys(Keys.TAB)

? ? ? driver.find_element_by_id("tinymce").send_keys(editbody)

15.非input文件上傳(SendKeys):

? (1)sendkeys安裝步驟:

? ? 1.sendkeys安裝:

? ? ? 輸入命令:pip install sendkeys.

? ? 2.如果安裝的時候報錯:micsoft visual c++ is required.Get it from http://aka.ms/vcpython27.的時候赫悄,只需要按照? ? ? 給定的路徑http://aka.ms/vcpython27下載文件即可原献,然后一路安裝即可。

? ? 3.如果出現(xiàn)successfully installed sendkeys_0.3字樣的時候埂淮,則代表文件安裝成功姑隅!

? ? <例># coding:utf-8

? ? ? ? ? from selenium import webdriver

? ? ? ? ? import SendKeys

? ? ? ? ? import time

? ? ? ? ? # 加載Firefox配置

? ? ? ? ? ? profileDir = r'C:\Users\xxxAppData\Roaming\Mozilla\Firefox\Profiles\1x41j9of.default'

? ? ? ? ? ? profile = webdriver.FirefoxProfile(profileDir)

? ? ? ? ? ? driver = webdriver.Firefox(profile)

? ? ? ? ? # 加載Chrome配置

? ? ? ? ? ? option = webdriver.ChromeOptions()

? ? ? ? ? ? option.add_argument('--user-data-dir=C:\Users\xxxAppData\Local\Google\Chrome\User Data')

? ? ? ? ? ? driver = webdriver.Chrome(chrome_options=option)

? ? ? ? ? ? driver.implicitly_wait(30)

? ? ? ? ? ? driver.get("http://www.cnblogs.com/yoyoketang/")

? ? ? ? ? ? driver.find_element_by_link_text("新隨筆").click()

? ? ? ? ? ? time.sleep(3)

? ? ? ? ? # 點開編輯器圖片

? ? ? ? ? ? driver.find_element_by_css_selector("img.mceIcon").click()

? ? ? ? ? ? time.sleep(3)

? ? ? ? ? # 定位所有iframe,取第二個

? ? ? ? ? ? iframe = driver.find_elements_by_tag_name('iframe')[1]

? ? ? ? ? # 切換到iframe上

? ? ? ? ? ? driver.switch_to_frame(iframe)

? ? ? ? ? # 文件路徑

? ? ? ? ? ? time.sleep(2)

? ? ? ? ? ? driver.find_element_by_class_name("qq-upload-button").click()

? ? ? ? ? # driver.find_element_by_name("file").click()? # 這里點文件上傳按鈕也是一個坑倔撞,我用它父元素定位了讲仰,參? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? 考上面一行

? ? ? ? ? ? time.sleep(5)

? ? ? ? ? # SendKeys方法輸入內(nèi)容

? ? ? ? ? ? SendKeys.SendKeys("D:\\test\\jie1\\blog\\12.png")? # 發(fā)送文件地址

? ? ? ? ? ? time.sleep(1)

? ? ? ? ? ? SendKeys.SendKeys("{ENTER}")? # 發(fā)送回車鍵

? ? ? ? ? ? time.sleep(1)

? ? ? ? ? ? SendKeys.SendKeys("{ENTER}")? ? # 因為我的電腦是搜索輸入法,所以多按一次回車

? ? ? ? ? ? driver.quit()

16.文件上傳(send_keys):

? 文件上傳是web頁面上很常見的一個功能痪蝇,一般分兩個場景:一種是input標簽鄙陡,這種可以用selenium提供的send_keys()方法輕? 松解決;另外一種非input標簽實現(xiàn)起來比較困難霹俺,可以借助autoit工具或者SendKeys第三方庫柔吼。

? ? 方法一:識別上傳按鈕

? ? ? ? 1.點開博客園編輯器里的圖片上傳按鈕,彈出”上傳本地圖片”框丙唧。

? ? ? ? 2.用firebug查看按鈕屬性愈魏,這種上傳圖片按鈕有個很明顯的標識,它是一個input標簽想际,并且type屬性的值為file培漏。只要? ? ? ? ? 找到這兩個標識,我們就可以直接用send_keys()方法上傳文件了胡本。

? ? ? 方法二:定位iframe

? ? ? ? 1.這里定位圖片上傳按鈕情況有點復(fù)雜牌柄,首先它是在iframe上。

? ? ? ? 2.這個iframe的id是動態(tài)的侧甫,且沒有name屬性珊佣,其它屬性也不是很明顯蹋宦。

? ? ? ? 3.通過搜索發(fā)現(xiàn),這個頁面上有兩個iframe咒锻,需要定位的這個iframe是處于第二個位置冷冗。

? ? ? ? 4.可以通過標簽定位所有的iframe標簽,然后取對應(yīng)的第幾個就可以了惑艇。

? ? ? <例> #coding:utf-8

? ? ? ? ? from selenium import webdriver

? ? ? ? ? import time

? ? ? ? ? profileDir=r'C:\Users\Gloria\AppData\Roaming\Mozilla\Firefox\Profiles\1x41j9of.default'

? ? ? ? ? profile=webdriver.Firefoxprofile(profiledir)

? ? ? ? ? driver=webdriver.Firefox(profile)

? ? ? ? ? driver.implicitly_wait(30)

? ? ? ? ? driver.get("http://www.cnblogs.com/yoyoketang/")

? ? ? ? ? driver.find_element_by_link_text("新隨筆").click()

? ? ? ? ? time.sleep(3)

? ? ? ? ? #點開編輯圖片

? ? ? ? ? ? driver.find_element_by_css_selector("img.mceIcon").click()

? ? ? ? ? ? time.sleep(3)

? ? ? ? ? #定位所有的iframe,取第二個

? ? ? ? ? ? iframe=driver.find_elements_by_tag_name('iframe')[1]

? ? ? ? ? #切換到iframe上

? ? ? ? ? ? driver.switch_to_frame(iframe)

? ? ? ? ? #文件路徑

? ? ? ? ? ? driver.find_element_by_name('file').send_keys

17.獲取元素屬性;

? (1)title的獲取方法蒿辙;

? ? <例> #coding:utf-8

? ? ? ? ? from selenium import webdriver

? ? ? ? ? import time

? ? ? ? ? driver=webdriver.Firefox()

? ? ? ? ? driver.implicitly_wait(10)

? ? ? ? ? driver.get(“http:www.baidu.com”)

? ? ? ? ? time.sleep(2)

? ? ? ? ? title=driver.title

? ? ? ? ? print title

? (2)通過driver.text獲取到文本;

? ? ? <例> #coding:utf-8

? ? ? ? ? from selenium import webdriver

? ? ? ? ? import time

? ? ? ? ? driver=webdriver.Firefox()

? ? ? ? ? driver.implicitly_wait(10)

? ? ? ? ? driver.get(“http:www.baidu.com”)

? ? ? ? ? time.sleep(2)

? ? ? ? ? title=driver.title

? ? ? ? ? print title

? ? ? ? ? text=driver.find_element_by_id(“setf”).text

? ? ? ? ? print text

? ? ? (3)獲取元素的標簽

? ? ? ? <例>獲取百度輸入框的標簽屬性

? ? ? ? ? tag=driver.find_element_by_id(“kw”).tag_name

? ? ? ? ? print tag

? ? ? (4)獲取元素的其它屬性;

? ? ? ? 獲取其它屬性方法:get_attribute("屬性"),這里的參數(shù)可以是class滨巴、name等任意屬性.

? ? ? ? ? <例>獲取百度輸入框的class屬性;

? ? ? ? ? ? ? name=driver.find_element_by_id(“kw”).get_attribute(“class”)

? ? ? ? ? ? ? print name

? ? ? (5)獲取輸入框內(nèi)的文本值;

? ? ? ? ? 如果在百度輸入框輸入了內(nèi)容思灌,這里輸入框的內(nèi)容也是可以獲取到的.

? ? ? ? ? <例>獲取百度輸入框的內(nèi)容;

? ? ? ? ? ? driver.find_element_by_id(“kw”).send_keys(“yoyoketang”)

? ? ? ? ? ? value=drvier.find_element_by_id(“kw”).get_attribute(“value”)

? ? ? ? ? ? print value

? ? ? (6)獲取瀏覽器名稱;獲取瀏覽器名稱很簡單恭取,用driver.name就能獲取到.

? ? ? ? <例>#coding:utf-8

? ? ? ? ? ? ? from selenium import webdriver

? ? ? ? ? ? ? import time

? ? ? ? ? ? ? driver=webdriver.Firefox()

? ? ? ? ? ? ? driver.implicitly_wait(10)

? ? ? ? ? ? ? driver.get(“http:www.baidu.com”)

? ? ? ? ? ? ? time.sleep(2)

? ? ? ? ? ? ? title=driver.title

? ? ? ? ? ? ? print title

? ? ? ? ? ? ? print driver.name

18.爬頁面源碼(page_source)

? (1)有時候通過元素的屬性的查找頁面上的某個元素泰偿,可能不太好找,這時候可以從selenium的page_source方法可以獲取到頁? ? ? 面源碼秽荤。

? ? <例>#coding:utf-8

? ? ? ? from selenium import webdriver

? ? ? ? import re

? ? ? ? driver=webdriver.Firefox()

? ? ? ? driver.get(“http://www.cnblogs.com/yoyoketang/”)

? ? ? ? page=driver.page_source

? ? ? ? print page

? ? (2)re非貪婪模式:

? ? ? 1.這里需導(dǎo)入re模塊(正則表達式模塊)

? ? ? 2.用re的正則匹配:非貪婪模式

? ? ? 3.findall方法返回的是一個list集合

? ? ? 4.匹配出來之后發(fā)現(xiàn)有一些不是url鏈接甜奄,可以篩選下

? ? ? #“非貪婪匹配”,re.s('.'匹配字符窃款,包括換行符)”

? ? ? url_list=re.findall('href=\"(.*?)\"',page,re.s)

? ? ? for url in url_list:

? ? ? ? ? print url?

? ? (3)篩選url地址出來

? ? ? 1.加個if語句判斷,‘http’在url里面說明是正常的url地址了

? ? ? 2.把所有的url地址放到一個集合牍氛,就是我們想要的結(jié)果啦.

? ? ? #“非貪婪匹配”晨继,re.s('.'匹配字符,包括換行符)”

? ? ? url_list=re.findall('href=\"(.*?)\"',page,re.s)

? ? ? url_all=[]

? ? ? for url in url_list:

? ? ? ? ? if "http" in url:

? ? ? ? ? ? print url

? ? ? ? ? ? url_all.append(url)

? ? ? ? print url_all

19.cookie相關(guān)操作:

? (1)獲取cookies:get_cookies()

? ? 1.獲取cookies方法直接用:get_cookies()

? ? 2.先啟動瀏覽器搬俊,獲取cookies紊扬,打印出來發(fā)現(xiàn)是空:[]

? ? 3.打開博客首頁后,重新獲取cookies,打印出來唉擂,就有值了.

? ? <例># coding:utf-8

? ? ? ? from selenium import webdriver

? ? ? ? import time

? ? ? ? driver=webdriver.Firefox()

? ? ? ? #啟動瀏覽器后獲取cookies

? ? ? ? print driver.get_cookies()

? ? ? ? driver.get("http://www.cnblogs.com/yoyoketang/")

? ? ? ? #打開主頁后獲取cookies

? ? ? ? print driver.get_cookies()

? ? (2)登錄后的cookies:

? ? ? 1.先登錄博客園(這里登錄用自己的賬號和密碼吧)

? ? ? 2.重新獲取cookies餐屎,發(fā)現(xiàn)跟之前獲取的不一樣了

? ? ? 3.主要是找到這一個cookie,發(fā)現(xiàn)它的name和value發(fā)生了變化,這就是未登錄和已登錄的區(qū)別了(對比上下兩張圖)

? ? ? ? {u'name': u'.CNBlogsCookie', u'value': u'B7813EBA142142CE88CC8C0B33B239F566xxxx'}

? ? ? <例>

? ? ? ? ? #登錄后獲取cookies

? ? ? ? ? url="https://passport.cnbblogs.com/user/signin"

? ? ? ? ? driver.get(url)

? ? ? ? ? driver.implicitly_wait(30)

? ? ? ? ? driver.find_element_by_id("input1").send_keys(u"上和嫠睿—悠悠")

? ? ? ? ? driver.find_element_by_id("input2").send_keys(u"xxxxx")

? ? ? ? ? driver.find_element_by_id("signin").click()

? ? ? ? ? time.sleep(3)

? ? ? ? ? print driver.get_cookies()

? ? ? (3)獲取指定name的cookie:driver.get_cookie(name)

? ? ? ? 1.獲取cookies發(fā)現(xiàn)里面有多個cookie,有時候我們只需要其中的一個腹缩,把重要的提出來,比如登錄的cookie

? ? ? ? 2.這里用get_cookie(name)空扎,指定對應(yīng)的cookie的name值就行了藏鹊,比如博客園的:.CNBlogsCookie

? ? ? ? <例># 獲取指定的name的cookie

? ? ? ? ? ? ? print driver.get_cookie(name=".CNBlogsCookie")

? ? ? (4)清除指定cookie:delete_cookie()

? ? ? ? 1.為了進一步驗證上一步獲取到的就是登錄的cookie,可以刪除它看看頁面什么變化

? ? ? ? 2.刪除這個cookie后刷新頁面转锈,發(fā)現(xiàn)剛才的登錄已經(jīng)失效了盘寡,變成未登錄狀態(tài)了

? ? ? ? <例># 清除指定name的cookie

? ? ? ? ? ? driver.delete_cookie(name="CNBlogsCookie")

? ? ? ? ? ? print driver.get_cookies()

? ? ? ? ? ? # 為了驗證此cookie是登錄的,可以刪除后刷新頁面

? ? ? ? ? ? driver.refresh()

? ? ? ? (5)清除所有cookies:delete_all_cookies()

? ? ? ? ? 清除所有cookies后登錄狀態(tài)也失效了撮慨,cookies為空[];

? ? ? ? ? <例># 清除所有的cookie

? ? ? ? ? ? ? driver.delete_all_cookies()

? ? ? ? ? ? ? print driver.get_cookies()

? ? ? ? (6)cookie操作的幾個方法

? ? ? ? ? 1.get_cookies():獲取所有cookies

? ? ? ? ? 2.driver.get_cookie(name):獲取指定name的cookie:

? ? ? ? ? 3.清除指定cookie:delete_cookie()

? ? ? ? ? 4.delete_all_cookies():清除所有cookies

? ? ? ? ? 5.add_cookie(cookie_dict):添加cookie的值



20.繞過驗證碼(add_cookie)竿痰;

? 驗證碼這種問題是比較頭疼的脆粥,對于驗證碼的處理,不要去想破解方法影涉,這個驗證碼本來就是為了防止別人自動化登錄的冠绢。如果? 你能破解,說明你們公司的驗證碼嗎安全級別不高常潮,那就需要提高級別了弟胀。

? 對于驗證碼,要么是讓開發(fā)在測試環(huán)境弄個萬能的驗證碼喊式,如:1234孵户,要么就是盡量繞過去,如本篇介紹的添加cookie的方法岔留。

一夏哭、fiddler抓包

? ? 1.前一篇講到,登錄后會生成一個已登錄狀態(tài)的cookie献联,那么只需要直接把這個值添加到cookies里面就可以了竖配。

? ? 2.可以先手動登錄一次,然后抓取這個cookie里逆,這里就需要用抓包工具fiddler了

? ? 3.先打開博客園登錄界面进胯,手動輸入賬號和密碼(不要點登錄按鈕)

? ? 4.打開fiddler抓包工具,此時再點博客園登錄按鈕

? ? 5.登錄成功后原押,再查看cookie變化胁镐,發(fā)現(xiàn)多了兩組參數(shù),多的這兩組參數(shù)就是我們想要的诸衔,copy出來盯漂,一會有用

二.添加cookie方法:driver.add_cookie()

? ? 1.add_cookie(cookie_dict)方法里面參數(shù)是cookie_dict,說明里面參數(shù)是字典類型笨农。

? ? 2.源碼官方文檔介紹:

? ? add_cookie(self, cookie_dict):

? ? ? ? Adds a cookie to your current session.

? ? ? :Args:

? ? ? - cookie_dict: A dictionary object, with required keys - "name" and "value";

? ? ? ? optional keys - "path", "domain", "secure", "expiry"

? ? ? Usage:

? ? ? driver.add_cookie({'name' : 'foo', 'value' : 'bar'})

? ? ? driver.add_cookie({'name' : 'foo', 'value' : 'bar', 'path' : '/'})

? ? ? driver.add_cookie({'name' : 'foo', 'value' : 'bar', 'path' : '/', 'secure':True})

? ? 3.從官方的文檔里面可以看出就缆,添加cookie時候傳入字典類型就可以了,等號左邊的是name谒亦,等號右邊的是value竭宰。

? ? 4.把前面抓到的兩組數(shù)據(jù)(參數(shù)不僅僅只有name和value),寫成字典類型:

? ? ? {'name':'.CNBlogsCookie','value':'2C3AE01E461B2D2F1572D02CB936D77A053089AA2xxxx...'}

? ? ? {'name':'.Cnblogs.AspNetCore.Cookies','value':'CfDJ8Mmb5OBERd5FqtiQlKZZIG4HKz_Zxxx...'}

? 三诊霹、cookie組成結(jié)構(gòu)

? ? 1.用抓包工具fidller只能看到cookie的name和value兩個參數(shù)羞延,實際上cookie還有其它參數(shù)。

? ? 2.cookie參數(shù)組成脾还,以下參數(shù)是我通過get_cookie(name)獲取到的伴箩。

? ? ? cookie ={u'domain': u'.cnblogs.com',

? ? ? ? ? ? u'name': u'.CNBlogsCookie',

? ? ? ? ? ? u'value': u'xxxx',

? ? ? ? ? ? u'expiry': 1491887887,

? ? ? ? ? ? u'path': u'/',

? ? ? ? ? ? u'httpOnly': True,

? ? ? ? ? ? u'secure': False}

? ? ? name:cookie的名稱

? ? ? value:cookie對應(yīng)的值,動態(tài)生成的

? ? ? domain:服務(wù)器域名

? ? ? expiry:Cookie有效終止日期

? ? ? path:Path屬性定義了Web服務(wù)器上哪些路徑下的頁面可獲取服務(wù)器設(shè)置的Cookie

? ? ? httpOnly:防腳本攻擊

? ? ? secure:在Cookie中標記該變量鄙漏,表明只有當瀏覽器和Web Server之間的通信協(xié)議為加密認證協(xié)議時嗤谚,

? ? ? ? ? ? ? 瀏覽器才向服務(wù)器提交相應(yīng)的Cookie棺蛛。當前這種協(xié)議只有一種,即為HTTPS巩步。

? 四旁赊、添加cookie

? ? 1.這里需要添加兩個cookie,一個是.CNBlogsCookie椅野,另外一個是.Cnblogs.AspNetCore.Cookies终畅。

? ? 2.我這里打開的網(wǎng)頁是博客的主頁:http://www.cnblogs.com/yoyoketang,沒進入登錄頁竟闪。

? ? 3.添加cookie后刷新頁面,接下來就是見證奇跡的時刻了离福。

? ? ? # coding:utf-8

? ? ? ? from selenium import webdriver

? ? ? ? import time

? ? ? ? driver = webdriver.Firefox()

? ? ? ? driver.get("http://www.cnblogs.com/yoyoketang")

? ? ? ? # 添加cookie

? ? ? ? ? c1 = {u'domain': u'.cnblogs.com',

? ? ? ? ? ? ? u'name': u'.CNBlogsCookie',

? ? ? ? ? ? ? u'value': u'xxxx',

? ? ? ? ? ? ? u'expiry': 1491887887,

? ? ? ? ? ? ? u'path': u'/',

? ? ? ? ? ? ? u'httpOnly': True,

? ? ? ? ? ? ? u'secure': False}

? ? ? ? ? c2 = {u'domain': u'.cnblogs.com',

? ? ? ? ? ? ? u'name': u'.Cnblogs.AspNetCore.Cookies',

? ? ? ? ? ? ? u'value': u'xxxx',

? ? ? ? ? ? ? u'expiry': 1491887887,

? ? ? ? ? ? ? u'path': u'/',

? ? ? ? ? ? ? u'httpOnly': True,

? ? ? ? ? ? ? u'secure': False}

? ? ? ? ? ? ? driver.add_cookie(c1)? # 添加2個值

? ? ? ? ? ? ? driver.add_cookie(c2)

? ? ? ? ? ? ? time.sleep(3)? ? ? ? ? # 交流QQ群:232607095

? ? ? ? # 刷新下頁面就見證奇跡了

? ? ? ? ? ? ? driver.refresh()

? ? ? ? ? 有幾點需要注意:

? ? ? ? ? ? 1.登錄時候要勾選下次自動登錄按鈕。

? ? ? ? ? ? 2.add_cookie()只添加name和value炼蛤,對于博客園的登錄是不成功妖爷。

? ? ? ? ? ? 3.本方法并不適合所有的網(wǎng)站,一般像博客園這種記住登錄狀態(tài)的才會適合理朋。

21 JS處理滾動條絮识;

? selenium并不是萬能的,有時候頁面上操作無法實現(xiàn)的嗽上,這時候就需要借助JS來完成了次舌。比如下面的場景:

? 當頁面上的元素超過一屏后,想操作屏幕下方的元素炸裆,是不能直接定位到垃它,會報元素不可見的。這時候需要借助滾動條來拖動? 屏幕烹看,使被操作的元素顯示在當前的屏幕上。滾動條是無法直接用定位工具來定位的洛史。selenium里面也沒有直接的方法去控制? 滾動條惯殊,這時候只能借助J了,還好selenium提供了一個操作js的方法:execute_script()也殖,可以直接執(zhí)行js的腳本土思。

? 一、JavaScript簡介

? ? JavaScript是世界上最流行的腳本語言忆嗜,因為你在電腦己儒、手機、平板上瀏覽的所有的網(wǎng)頁捆毫,以及無數(shù)基于HTML5的手機App闪湾,? ? ? 交互邏輯都是由JavaScript驅(qū)動的。簡單地說绩卤,JavaScript是一種運行在瀏覽器中的解釋型的編程語言途样。? ?

? ? (參考鏈接江醇;http://www.w3school.com.cn/js/index.asp4)

? 二、控制滾動條高度

? ? 1.滾動條回到頂部:

? ? ? js="var q=document.getElementById('id').scrollTop=0"

? ? ? driver.execute_script(js)

? ? 2.滾動條拉到底部何暇;

? ? ? js="var q=document.documentElement.scrollTop=10000"

? ? ? driver.execute_script(js)

? ? 3.這里可以修改scrollTop 的值陶夜,來定位右側(cè)滾動條的位置,0是最上面裆站,10000是最底部条辟。

? 三、橫向滾動條

? ? 1.有時候瀏覽器頁面需要左右滾動(一般屏幕最大化后宏胯,左右滾動的情況已經(jīng)很少見了)羽嫡。

? ? 2.通過左邊控制橫向和縱向滾動條;

? ? ? scrollTo(x, y)js = "window.scrollTo(100,400);"

? ? ? driver.execute_script(js)

? ? 3.第一個參數(shù)x是橫向距離胳嘲,第二個參數(shù)y是縱向距離

? 四厂僧、Chrome瀏覽器

? ? 1.以上方法在Firefox上是可以的,但是用Chrome瀏覽器了牛,發(fā)現(xiàn)不管用颜屠。

? ? 2.Chrome瀏覽器解決辦法:

? ? ? js = "var q=document.body.scrollTop=0"

? ? ? driver.execute_script(js)

? 五、元素聚焦?

? ? ? 1.雖然用上面的方法可以解決拖動滾動條的位置問題鹰祸,但是有時候無法確定我需要操作的元素在什么位置甫窟,有可能每次打開? ? ? ? 的頁面不一樣,元素所在的位置也不一樣蛙婴,怎么辦呢粗井?

? ? ? 2.這個時候我們可以先讓頁面直接跳到元素出現(xiàn)的位置,然后就可以操作了街图。同樣需要借助JS去實現(xiàn)浇衬。

? ? ? 3.元素聚焦:

? ? ? ? target = driver.find_element_by_xxxx()

? ? ? ? driver.execute_script("arguments[0].scrollIntoView();", target)

? 六、獲取瀏覽器名稱:driver.name

? ? ? 1.為了解決不同瀏覽器操作方法不一樣的問題餐济,可以寫個函數(shù)去做兼容耘擂。

? ? ? 2.先用driver.name獲取瀏覽器名稱,然后用if語句做個判斷

? ? ? # coding:utf-8

? ? ? ? from selenium import webdriver

? ? ? ? driver=webdriver.Firefox()

? ? ? ? driver.get(“https://www.baidu.com”)

? ? ? ? print driver.name

? ? 七絮姆、兼容性

? ? ? ? 1.兼容谷歌和firefox/IE

? ? ? ? #回到頂部

? ? ? ? ? def scroll_top():

? ? ? ? ? ? ? if driver.name=="chrome"

? ? ? ? ? ? ? ? ? js="var q=document.body.scrollTop=0"

? ? ? ? ? ? ? else:

? ? ? ? ? ? ? ? ? js="var q=document.documentElement.scrollTop=0"

? ? ? ? ? ? ? return driver.execute_script(js)

? ? ? ? #拉到底部

? ? ? ? ? def scroll_foot():

? ? ? ? ? ? ? if driver.name=="chrome"

? ? ? ? ? ? ? ? ? js="var q=document.body.scrollTop=10000"

? ? ? ? ? ? ? else:

? ? ? ? ? ? ? ? ? js="var q=document.documentElement.scrollTop=10000"

? ? ? ? ? ? ? return driver.execute_script(js)

? ? ? 八醉冤、scrollTo函數(shù)

? ? ? ? ? --scrollHeight 獲取對象的滾動高度。

? ? ? ? ? --scrollLeft 設(shè)置或獲取位于對象左邊界和窗口中目前可見內(nèi)容的最左端之間的距離篙悯。

? ? ? ? ? --scrollTop 設(shè)置或獲取位于對象最頂端和窗口中可見內(nèi)容的最頂端之間的距離蚁阳。

? ? ? ? ? --scrollWidth 獲取對象的滾動寬度。

? ? ? ? ? scrollTo函數(shù)不存在兼容性問題鸽照,直接用這個函數(shù)就可以了;

? ? ? ? ? ? #滾動到底部

? ? ? ? ? js = "window.scrollTo(0,document.body.scrollHeight)"

? ? ? ? ? driver.execute_script(js)

? ? ? ? ? ? #滾動到頂部

? ? ? ? ? ? js = "window.scrollTo(0,0)"?

? ? ? ? ? driver.execute_script(js)

22.JS處理富文本;

? 一螺捐、加載配置

? ? 1.打開博客園寫隨筆,首先需要登錄,這里為了避免透露個人賬戶信息归粉,我直接加載配置文件椿疗,免登錄了。

? ? ? 不懂如何加載配置文件的糠悼,看加載firefox配置.

? ? ? # coding:utf-8

? ? ? ? from selenium import webdriver

? ? ? ? from selenium.webdriver.common.keys import keys

? ? ? ? import time

? ? ? ? profileDir=r'C:\xxx...\Firefox\profiles\1x41j9of.default'

? ? ? ? profile=webdriver.Firefoxprofile(profileDir)

? ? ? ? driver=webdriver.Firefox(profile)

? 二届榄、打開編輯界面

? ? 1.博客首頁地址:bolgurl = "http://www.cnblogs.com/"

? ? 2.我的博客園地址:yoyobolg = bolgurl + "yoyoketang"

? ? 3.點擊“新隨筆”按鈕,id=blog_nav_newpost?

? ? ? bolgurl= "http://www.cnblogs.com/"

? ? ? yoyobolg = bolgurl + "yoyoketang"

? ? ? driver.get(yoyobolg)

? ? ? driver.find_element_by_id("blog_nav_newpost").click()

? ? 三倔喂、定位iframe

? ? 1.打開編輯界面后先不要急著輸入內(nèi)容铝条,先sleep幾秒鐘

? ? 2.輸入標題,這里直接通過id就可以定位到席噩,沒什么難點

? ? 3.接下來就是重點要講的富文本的編輯班缰,這里編輯框有個iframe,所以需要先切換?

? ? 四悼枢、js輸入中文

? ? 1.這里定位編輯正文是定位上圖的紅色框框位置body部分埠忘,也就是id=tinymce

? ? 2.定位到之后,用js的方法直接輸入馒索,無需切換iframe

? ? 3.直接點保存按鈕莹妒,無需再切回來.

? ? <完整代碼>

? ? # coding:utf-8

? ? from selenium import webdriver

? ? from selenium.webdriver.common.keys import Keys

? ? ? import time

? ? ? # profileDir路徑對應(yīng)直接電腦的配置路徑

? ? ? profileDir = r'C:\xxx\xxx\AppData\Roaming\Mozilla\Firefox\Profiles\1x41j9of.default'

? ? ? profile = webdriver.FirefoxProfile(profileDir)

? ? ? driver = webdriver.Firefox(profile)

? ? ? bolgurl = "http://www.cnblogs.com/"

? ? ? yoyobolg = bolgurl + "yoyoketang"

? ? ? driver.get(yoyobolg)

? ? ? driver.find_element_by_id("blog_nav_newpost").click()

? ? ? ? time.sleep(5)

? ? ? edittile = u"Selenium2+python自動化23-富文本"

? ? ? editbody = u"這里是發(fā)帖的正文"

? ? ? driver.find_element_by_id("Editor_Edit_txbTitle").send_keys(edittile)

? ? ? ? body = "這里是通過js發(fā)的正文內(nèi)容"

? ? # js處理iframe問題(js代碼太長了,我分成兩行了)

? ? ? ? js = 'document.getElementById("Editor_Edit_EditorBody_ifr")' \

? ? ? ? ? ? '.contentWindow.document.body.innerHTML="%s"' % body

? ? ? ? ? driver.execute_script(js)

? ? # 保存草稿

? ? ? ? ? driver.find_element_by_id("Editor_Edit_lkbDraft").click()

23 js處理日歷控件(修改readonly屬性)绰上;

? <完整代碼>

? ? from selenium import webdriver

? ? driver = webdriver.Firefox()

? ? driver.get("https://kyfw.12306.cn/otn/index/init")

? ? # 去掉元素的readonly屬性

? ? ? js = 'document.getElementById("train_date").removeAttribute("readonly");'

? ? ? driver.execute_script(js)

? ? # 用js方法輸入日期

? ? ? js_value = 'document.getElementById("train_date").value="2016-12-25"'

? ? ? driver.execute_script(js_value)

? ? # # 清空文本后輸入值

? ? # driver.find_element_by_id("train_date").clear()

? ? # driver.find_element_by_id("train_date").send_keys("2016-12-25")

24.js處理內(nèi)嵌div滾動條旨怠;

? 一.縱向滾動;

? ? 1.這個是div的屬性:<div id="yoyoketang" name="yoyo" class="scroll">

? ? 2.這里最簡單的通過id來定位蜈块,通過控制 scrollTop的值來控制滾動條高度

? ? 3.運行下面代碼鉴腻,觀察頁面是不是先滾動到底部,過五秒再回到頂部百揭。(get里面地址? ? ? 是瀏覽器打開該頁面的地址)

? ? <例># coding:utf-8

? ? ? ? ? ? from selenium import webdriver

? ? ? ? ? ? import time

? ? ? ? ? ? driver=webdriver.Firefox()

? ? ? ? ? ? driver.get("file:///C:/Users/Gloria/Desktop/div.html")

? ? ? ? ? # 縱向底部

? ? ? ? ? ? js1=‘document.getElementById("yoyoketang").scrollTop=10000’

? ? ? ? ? ? driver.execute_script(js1)

? ? ? ? ? ? time.sleep(5)

? ? ? ? ? ? # 縱向頂部

? ? ? ? ? ? ? js1=‘document.getElementById("yoyoketang").scrollTop=0’

? ? ? ? ? ? ? driver.execute_script(js1)

? 二.橫向滾動爽哎;

? ? ? 先通過id來定位,通過控制scrollLeft的值來控制滾動條高度.

? ? ? <例># coding:utf-8

? ? ? ? ? ? from selenium import webdriver

? ? ? ? ? ? import time

? ? ? ? ? ? driver=webdriver.Firefox()

? ? ? ? ? ? driver.get("file:///C:/Users/Gloria/Desktop/div.html")

? ? ? ? ? # 橫向右側(cè)

? ? ? ? ? ? js3=‘document.getElementById("yoyoketang").scrollLeft=10000’

? ? ? ? ? ? driver.execute_script(js3)

? ? ? ? ? ? time.sleep(5)

? ? ? ? ? ? # 橫向左側(cè)側(cè)

? ? ? ? ? ? ? js4=‘document.getElementById("yoyoketang").scrollLeft=0’

? ? ? ? ? ? ? driver.execute_script(js4)

? ? 三.用class屬性定位器一;

? ? ? js用class屬性定位倦青,返回的是一個list對象,這里取第一個就可以了盹舞。

? ? ? 注意;element和elements是不一樣的.

? ? <例> # coding:utf-8

? ? ? ? ? ? from selenium import webdriver

? ? ? ? ? ? import time

? ? ? ? ? ? driver=webdriver.Firefox()

? ? ? ? ? ? driver.get("file:///C:/Users/Gloria/Desktop/div.html")

? ? ? ? ? ? # 獲取的class返回的是list對象隘庄,取list的第一個

? ? ? ? ? ? js5=‘document.getElementsByClassName("scroll")? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? [0].scrollTop=10000’

? ? ? ? ? ? driver.execute_script(js5)

? ? ? ? ? ? time.sleep(5)

? ? ? ? ? ? # 控制橫向滾動條位置

? ? ? ? ? ? js6=‘document.getElementsByClassName("scroll")? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? [0].scrollLeft=10000’

? ? ? ? ? ? driver.execute_script(js6)

? ? ? 有時候很多元素屬性都一樣時候踢步,就可以用復(fù)數(shù)定位,取對應(yīng)的第幾個就可以了丑掺。

25 js處理多窗口;

? js去掉target="_blank"屬性

? ? 1.第一步為了先登錄获印,我這里加載配置文件免登錄了.

? ? 2.這里用到j(luò)s的定位方法,定位該元素的class屬性

? ? 3.定位到該元素后直接修改target屬性值為空.

? ? <例># coding:utf-8

? ? ? ? ? ? from selenium import webdriver

? ? ? ? ? ? from selenium.webdriver.common.keys import Keys

? ? ? ? ? ? import time

? ? ? ? ? # 加載配置文件免登錄

? ? ? ? ? ? profileDir = r'C:\Users\Gloria\AppData\Roaming\Mozilla\Firefox? ? ? ? ? ? ? ? ? ? ? ? ? ? \Profiles\1x41j9of.default'

? ? ? ? ? ? profile = webdriver.FirefoxProfile(profileDir)

? ? ? ? ? ? driver = webdriver.Firefox(profile)

? ? ? ? ? ? driver.get("https://www.baidu.com/")

? ? ? ? ? # 修改元素的target屬性

? ? ? ? ? ? js = 'document.getElementsByClassName("mnav")[0].target="";'

? ? ? ? ? ? driver.execute_script(js)

? ? ? ? ? ? driver.find_element_by_link_text("糯米").click()

? ? ? (注意:并不是所有的鏈接都適用于本方法街州,本篇只適用于有這個target="_blank"? ? ? ? ? ? ? 屬性鏈接情況兼丰。)

26 js解決click失效問題:

? <例># coding:utf-8

? ? ? ? ? from selenium import webdriver

? ? ? ? ? from selenium.webdriver.common.action_chains import ActionChains

? ? ? ? ? from selenium.webdriver.support.select import Select

? ? ? ? ? import time

? ? ? ? ? driver = webdriver.Firefox()

? ? ? ? ? url = "https://www.baidu.com"

? ? ? ? ? driver.get(url)

? ? ? ? ? time.sleep(3)

? ? ? ? ? mouse = driver.find_element("link text", "設(shè)置")

? ? ? ? ? ActionChains(driver).move_to_element(mouse).perform()

? ? ? ? ? time.sleep(3)

? ? ? ? ? driver.find_element("link text", "搜索設(shè)置").click()

? ? ? ? ? time.sleep(3)

? ? ? ? ? s = driver.find_element("id", "nr")

? ? ? ? ? Select(s).select_by_visible_text("每頁顯示50條")

? ? ? ? ? # 方法一:先點父元素 交流QQ群:232607095

? ? ? ? ? # driver.find_element("id", "gxszButton").click()

? ? ? ? ? # driver.find_element("class name", "prefpanelgo").click()

? ? ? ? ? # 方法二:用js直接去點擊 .

? ? ? ? ? ? js = 'document.getElementsByClassName("prefpanelgo")[0].click();'

? ? ? ? ? ? driver.execute_script(js)

27.18種定位方法總結(jié):

? 一玻孟、十八種定位方法:

? ? (1)常用的八種元素定位方式:

? ? ? 1.id定位:find_element_by_id(self, id_)

? ? ? 2.name定位:find_element_by_name(self, name)

? ? ? 3.class定位:find_element_by_class_name(self, name)

? ? ? 4.tag定位:find_element_by_tag_name(self, name)

? ? ? 5.link定位:find_element_by_link_text(self, link_text)

? ? ? 6.partial_link定位find_element_by_partial_link_text(self, link_text)

? ? ? 7.xpath定位:find_element_by_xpath(self, xpath)

? ? ? 8.css定位:find_element_by_css_selector(self, css_selector)

? ? (2)這八種是復(fù)數(shù)形式;

? ? ? 9.id復(fù)數(shù)定位find_elements_by_id(self, id_)

? ? ? 10.name復(fù)數(shù)定位find_elements_by_name(self, name)

? ? ? 11.class復(fù)數(shù)定位find_elements_by_class_name(self, name)

? ? ? 12.tag復(fù)數(shù)定位find_elements_by_tag_name(self, name)

? ? ? 13.link復(fù)數(shù)定位find_elements_by_link_text(self, text)

? ? ? 14.partial_link復(fù)數(shù)定位find_elements_by_partial_link_text(self,? ? ? ? ? link_text)

? ? ? 15.xpath復(fù)數(shù)定位find_elements_by_xpath(self, xpath)

? ? ? 16.css復(fù)數(shù)定位find_elements_by_css_selector(self, css_selector)

? (3)這兩種就是快失傳了的鳍征;

? ? ? 17.find_element(self, by='id', value=None)

? ? ? 18.find_elements(self, by='id', value=None)

二黍翎、element和elements傻傻分不清

? ? 1.element方法定位到是是單數(shù),是直接定位到元素

? ? 2.elements方法是復(fù)數(shù)艳丛,這個學(xué)過英文的都知道匣掸,定位到的是一組元素,返回的是? ? ? list隊列.

? ? 3.可以用type()函數(shù)查看數(shù)據(jù)類型.

? ? ? <參考代碼>

? ? ? # coding:utf-8

? ? ? ? from selenium import webdriver

? ? ? ? driver = webdriver.Firefox()

? ? ? ? driver.get("http://www.baidu.com")

? ? ? # 這里是定位的單個id

? ? ? ? element = driver.find_element_by_id("kw")

? ? ? ? print type(element)

? ? ? ? print element

? ? ? # 這里定位是多個class

? ? ? ? elements = driver.find_elements_by_class_name("mnav")

? ? ? ? print type(elements)

? ? ? ? print elements

? ? ? # 這里用的css語法

? ? ? ? s = driver.find_elements("css selector", ".mnav")

? ? ? # '地圖'在第四個位置

? ? ? ? print s[3].text

? ? ? ? s[3].click()

? ? ? # 這個寫法也是可以的

? ? ? # driver.find_elements("css selector", ".mnav")[3].click()

28.查看webdriver API(帶翻譯)

? 一氮双、pydoc

? ? ? 1.到底什么是pydoc? ,這個是準確的解釋:Documentation generator and online? ? ? ? help system. pydoc是Python自帶的模塊碰酝,主要用于從python模塊中自動生成文? ? ? ? 檔,這些文檔可以基于文本呈現(xiàn)的戴差、也可以生成WEB頁面的送爸,還可以在服務(wù)器上以? ? ? 瀏覽器的方式呈現(xiàn)!簡而言之暖释,就是幫你從代碼和注釋自動生成文檔的工具袭厂。

? ? ? 2.舉個栗子,我需要查看python里面open函數(shù)的功能和語法饭入,打開cmd,輸入:python? ? ? ? -m pydoc open

? ? ? 3.-m參數(shù):python以腳本方法運行模塊嵌器;

? ? ? ? >>python -m pydoc open

? ? 二、啟動server谐丢;

? ? ? ? 1.打開cmd命令行爽航,輸入:python -m pydoc -p 6666

? ? ? ? 2.-p參數(shù):這個表示在本機上啟動服務(wù)

? ? ? ? 3.6666參數(shù):這個是服務(wù)端口號,隨意設(shè)置

? ? ? ? ? 打開后乾忱,界面會出現(xiàn)一個地址:http://localhost:6666/,在瀏覽器直接打開讥珍。

? ? 三、瀏覽器查看文檔

? ? ? 1.在瀏覽器輸入:http://localhost:6666/

? ? ? 2.Built-in Moudles :這個是python自帶的模塊.

? ? 四窄瘟、webdriver API:

? ? ? 1.找到這個路徑:python2.7\lib\site-packages衷佃,點開selenium

? ? ? 2.打開的selenium>webdriver>firefox>webdriver,最終路徑:? ? ? ? ? ? ? ? ? http://localhost:6666/selenium.webdriver.firefox.webdriver.html

? ? ? 3.最終看到的這些就是selenium的webdriver API幫助文檔啦.

29.練習(xí)題;

? 一.去掉頁面動態(tài)窗.

? 1蹄葱、alert彈窗氏义;

? ? 這種彈窗是最簡單的一種,Selenium里有自帶的方法來處理它图云,用switch_to.alert? ? 先定位到彈窗惯悠,然后使用一系列方法來操作:

? ? accept - 點擊【確認】按鈕

? ? dismiss - 點擊【取消】按鈕(如有按鈕)

? ? send_keys - 輸入內(nèi)容(如有輸入框)

? ? 這里舉一個菜鳥教程上的一個例子:

? ? http://www.runoob.com/try/try.php?filename=tryjs_alert,

? ? 在頁面左邊點擊【顯示警告框】就會彈出一個alert彈窗:

? ? 我們用以下代碼就能實現(xiàn)切換至彈窗并點擊【確定】按鈕的效果:

? ? al = driver.switch_to_alert() al.accept()

? ? 這里這個switch_to_alert()其實是舊寫法竣况,照理應(yīng)該是用switch_to.alert()克婶,但是? ? 新寫法卻會報錯,目前猜測是版本問題,可能不支持新寫法情萤,這里就先用舊寫法鸭蛙。

? ? <例># encoding:utf-8

? ? ? ? ? from selenium import webdriver

? ? ? ? ? import time

? ? ? ? ? driver = webdriver.Firefox()

? ? ? ? ? driver.get("http://www.runoob.com/try/try.php?filename=tryjs_alert")? ? ? ? ? ? driver.switch_to.frame("iframeResult")

? ? ? ? ? driver.find_element_by_xpath("html/body/input").click()

? ? ? ? ? time.sleep(1) al = driver.switch_to_alert()

? ? ? ? ? time.sleep(1) al.accept()

? 2、自定義彈窗

? ? 由于alert彈窗不美觀筋岛,現(xiàn)在大多數(shù)網(wǎng)站都會使用自定義彈窗娶视,使用Selenium自帶的? ? ? 方法就駕馭不了了,此時就要搬出JS大法泉蝌。這里舉一個新世界教育官網(wǎng)首頁的例子? ? ? ? (http://sh.xsjedu.org):

? ? ? <例># encoding:utf-8

? ? ? ? ? ? ? from selenium import webdriver

? ? ? ? ? ? ? import time

? ? ? ? ? ? ? driver = webdriver.Firefox()

? ? ? ? ? ? ? driver.get("http://sh.xsjedu.org/")

? ? ? ? ? ? ? time.sleep(1)

? ? ? ? ? ? ? js='document.getElementById? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ("doyoo_monitor").style.display="none";'

? ? ? ? ? ? ? driver.execute_script(js)

? ? 二.定位百度-更多產(chǎn)品歇万;

? ? ? <例># coding:utf-8

? ? ? ? ? ? from selenium import webdriver

? ? ? ? ? ? from selenium.webdriver.common.action_chains import ActionChains

? ? ? ? ? ? import time

? ? ? ? ? ? driver = webdriver.Firefox()

? ? ? ? ? ? url = "https://www.baidu.com"

? ? ? ? ? ? driver.get(url)

? ? ? ? ? ? driver.maximize_window()

? ? ? ? ? ? time.sleep(2)

? ? ? ? ? ? e = driver.find_element_by_link_text("更多產(chǎn)品")

? ? ? ? ? ? ActionChains(driver).move_to_element(e).perform()

? ? ? ? ? ? time.sleep(1)

? ? ? ? ? ? # ele = driver.find_element_by_name("tj_more")

? ? ? ? ? ? # 經(jīng)確認,是可以定位到元素的

? ? ? ? ? ? # print ele.text

? ? ? ? ? ? # 這一步點擊失效了

? ? ? ? ? ? # ele.click()?

? ? ? ? ? ? # js大法好勋陪,完美解決ckick失效問題

? ? ? ? ? ? ? js = "document.getElementsByName('tj_more')[0].click()"

? ? ? ? ? ? ? driver.execute_script(js)

? ? 三.獲取百度聯(lián)系詞贪磺;

? (1)定位輸入框聯(lián)想詞

? ? 1.首先在百度輸入框輸入關(guān)鍵詞,如:博客诅愚,然后輸入框下方會自動匹配出關(guān)鍵詞寒锚。

? ? 2.這時候可以用firebug工具定位到聯(lián)想出來的詞,可以看到下方匹配出來的詞都有共同的class屬性违孝,這時候就可以全部定? ? ? 位到了刹前。

? (2)打印全部匹配出來的詞,可以通過get_attribute()方法獲取到文本信息

? (3)點擊其中一個

? ? ? 1.點擊其中的一個聯(lián)想詞雌桑,如:第二個

? ? ? 2.這里可以先加一個判斷喇喉,如果獲取到了就點擊,沒獲取到就不點擊了校坑,以免拋異常拣技。

? ? ? (如果想依次點擊,用for循環(huán)就可以了)

? ? ? <例>

? ? ? # coding:utf-8

? ? ? ? from selenium import webdriver

? ? ? ? import time

? ? ? ? driver = webdriver.Firefox()

? ? ? ? driver.implicitly_wait(10)

? ? ? ? driver.get("http://www.baidu.com")

? ? ? ? ? time.sleep(1)

? ? ? ? driver.find_element_by_id("kw").send_keys(u"博客")

? ? ? # 獲取百度輸入框的

? ? ? ? time.sleep(1)

? ? ? ? bd = driver.find_elements_by_class_name("bdsug-overflow")

? ? ? ? ? ? ? for i in bd:

? ? ? ? print i.get_attribute("data-key")

? ? ? # 點擊其中的一個耍目,如:第二個

? ? ? ? ? if len(bd) > 1:

? ? ? ? ? bd[1].click()

? ? ? # 打印當前頁面url

? ? ? ? ? print driver.current_url

? ? ? ? ? ? else:

? ? ? ? ? ? ? print "未獲取到匹配的詞"

30.js幾種定位方法總結(jié);

? 一膏斤、以下總結(jié)了5種js定位的方法

? ? ? 除了id是定位到的是單個element元素對象,其它的都是elements返回的是list對象.

? ? 1.通過id獲取

? ? ? document.getElementById(“id”)

? ? 2.通過name獲取

? ? ? document.getElementsByName(“Name”)

? ? ? 返回的是list

? ? 3.通過標簽名選取元素

? ? ? document.getElementsByTagName(“tag”)

? ? 4.通過CLASS類選取元素

? ? ? document.getElementsByClassName(“class”)

? ? ? 兼容性:IE8及其以下版本的瀏覽器未實現(xiàn)getElementsByClassName方法

? ? 5.通過CSS選擇器選取元素

? ? ? document.querySelectorAll(“css selector")

? ? ? 兼容性:IE8及其以下版本的瀏覽器只支持CSS2標準的選擇器語法

? 二邪驮、id定位

? ? 1.定位博客首頁的管理按鈕:id="blog_nav_contact"

? ? 2.js的定位語法里面id定位獲取的是單個元素對象莫辨,可以直接用click()方法點擊元素.

? 三、class定位

? ? 1.js里面class定位獲取到是是一個list列表對象.

? ? 2.操作元素的話通過下標取對應(yīng)的第幾個值毅访,如果只用一個那就取下標[0].

? ? 3.定位到輸入框沮榜,可以直接用value="xxx"方法輸入內(nèi)容.

? ? 4.ByName和ByTagName跟上面class一樣,都是定位的一組元素.

? 四喻粹、CSS選擇器

? ? ? 1.css選擇器定位到的也是一組元素敞映,語法跟前面學(xué)到的css語法是一樣的.

? ? ? <例>

? ? ? ? ? # coding: utf-8

? ? ? ? ? ? from selenium import Webdriver

? ? ? ? ? ? import time

? ? ? ? ? ? driver = webdriver.Firefox()

? ? ? ? ? ? driver.get("http://cnblogs.com/yoyoketang")

? ? ? ? ? #定位首頁管理按鈕:id=blog_nav_contact

? ? ? ? ? ? js1 = 'document.getElementById("blog_nav_contact")'.click;'

? ? ? ? ? ? driver.execute_script(js1)

? ? ? ? ? #輸入賬號

? ? ? ? ? ? js2 = 'document.getElementsByClassName("input-text")[0].value="悠悠";'

? ? ? ? ? ? driver.execute_script(js2)

? ? ? ? ? #輸入密碼

? ? ? ? ? ? js3 = 'document.getElementsByClassName("input-text")[1].value="xxx";'

? ? ? ? ? ? driver.execute_script(js3)

? ? ? ? ? #勾選記住密碼

? ? ? ? ? ? js4 = 'document.getElementsByName("remember_me")[0].click();'

? ? ? ? ? ? driver.execute_script(js4)

? ? ? ? ? #點擊登錄按鈕

? ? ? ? ? ? js5 = 'document.querySelectorAll(#signin)[0].click();'

? ? ? ? ? ? driver.execute_script(js5)

31.定位的坑:class屬性有空格.

? ? 有些class屬性中間有空格,如果直接復(fù)制過來定位是會報錯的InvalidSelectorException: Message:

? ? The given selector u-label f-dn is either invalid or does not result in a WebElement. The following error? ? ? ? occurred:

? ? InvalidSelectorError: Compound class names not permitted.這個報錯意思是說定位語法錯了磷斧。

? ? 一、定位帶空格的class屬性

? ? ? ? 1.以126郵箱為例:http://mail.126.com/,定位賬號輸入框.

? ? ? ? 2.如果直接復(fù)制過來用class屬性定位是會報錯的.

? ? 二弛饭、class屬性科普

? ? ? ? 1.class屬性中間的空格并不是空字符串冕末,那是間隔符號,表示的是一個元素有多個class的屬性名稱侣颂,在整個HTML文檔? ? ? ? ? 档桃,使用CSS中的同一個class類可能是一個或多個!

? ? ? ? ? (class屬性是比較特殊的一個憔晒,除了這個有多個屬性外藻肄,其它的像name,id是沒多個屬性的)

? ? ? ? 2.想補習(xí)html基礎(chǔ)知識的可以參考菜鳥教程:http://www.runoob.com/html/html-attributes.html

? ? 三、class定位

? ? ? ? 既然知道class屬性有空格是多個屬性了拒担,那定位的時候取其中的一個就行(并且要唯一)嘹屯,也就是說class="j-? ? ? ? ? ? ? ? inputtext dlemail",取j-inputtext 和dlemail都是可以的从撼,這樣這個class屬性在頁面上唯一就行.

? ? ? ? 那么問題來了:如何才知道這個元素的某個屬性是不是在頁面上是唯一的呢州弟?

? ? 四、判斷元素唯一性

? ? ? ? F12切換到HTML界面低零,在搜索框輸入關(guān)鍵字搜索婆翔,如:j-inputtext,然后按回車搜索掏婶,看頁面上有幾個class屬性中有? ? ? ? ? j-inputtext這個屬性的啃奴,就知道是不是唯一的了。

? ? 五雄妥、class屬性不唯一怎么辦

? ? ? ? 如果這個class的多個屬性都不是唯一的咋辦呢最蕾,元素不唯一也不用怕,可以用復(fù)數(shù)定位茎芭,把所有的相同元素定位出來? ? ? ? 揖膜,按下標取第幾個就行。

? ? 六梅桩、css定位

? ? ? ? 1.css來定位class屬性的元素前面加個點(.)就行,然后空格變成點(.)就能定位了.

? ? ? ? 2.當然css也可以取class屬性的其中一個屬性(頁面上唯一的)來定位壹粟,定位方法是靈活多變的.

? ? ? <參考代碼>

? ? ? ? # coding:utf-8

? ? ? ? ? from selenium import webdriver

? ? ? ? ? driver = webdriver.Firefox()

? ? ? ? ? driver.get("http://mail.126.com/")

? ? ? ? ? driver.implicitly_wait(20)

? ? ? ? ? driver.switch_to.frame("x-URS-iframe")

? ? ? ? # 方法一:取單個class屬性

? ? ? ? ? driver.find_element_by_class_name("dlemail").send_keys("yoyo")

? ? ? ? ? driver.find_element_by_class_name("dlpwd").send_keys("12333")

? ? ? ? # 方法二:定位一組取下標定位(乃下策)

? ? ? ? # driver.find_elements_by_class_name("j-inputtext")[0].send_keys("yoyo")

? ? ? ? # driver.find_elements_by_class_name("j-inputtext")[1].send_keys("12333")

? ? ? ? # 方法三:css定位

? ? ? ? # driver.find_element_by_css_selector(".j-inputtext.dlemail").send_keys("yoyo")

? ? ? ? # driver.find_element_by_css_selector(".j-inputtext.dlpwd").send_keys("123")

? ? ? ? # 方法四:取單個class屬性也是可以的

? ? ? ? # driver.find_element_by_css_selector(".dlemail").send_keys("yoyo")

? ? ? ? # driver.find_element_by_css_selector(".dlpwd").send_keys("123")

32.jquery定位(簡直逆天)

? ? 一、jquery搜索元素宿百;

? ? ? ? 1.按F12進控制臺

? ? ? ? 2.點全部按鈕

? ? ? ? 3.右側(cè)如果沒出現(xiàn)輸入框趁仙,就點下小箭頭按鈕

? ? ? ? 4.輸入框輸入jquery定位語法,如:$("#input1")

? ? ? ? 5.點運行按鈕

? ? ? ? 6.左邊會出現(xiàn)定位到的元素垦页,如果有多個會以list列表的形式展示出雀费。

? ? 二、jquery定位語法痊焊;

? ? ? ? 1.jquery語法可以學(xué)下w3school的教程:http://www.w3school.com.cn/jquery/jquery_syntax.asp

? ? ? ? 2.格式如下:

? ? ? ? ? $(selector).action()

? ? ? ? ? --selector:這里的定位語法和css的定位語法是一致的盏袄,如:id就是#忿峻,class就是點(.),tag標簽名前面就無符號

? ? ? ? ? --action:這個是定位元素之后的操作行為事件,如click.

? ? 三辕羽、jquery行為逛尚;

? ? ? 1.發(fā)送文本語法:$(selector).val(輸入文本的值)

? ? ? 2.清空文本語法:$(selector).val('')? # 空字符串,兩個單引號

? ? ? 3.點擊按鈕:$(selector).click()

? ? ? ? <參考代碼>

? ? ? # coding:utf-8

? ? ? ? from selenium import webdriver

? ? ? ? import time

? ? ? ? driver = webdriver.Firefox()

? ? ? ? driver.get("https://passport.cnblogs.com/user/signin")

? ? ? ? driver.implicitly_wait(20)

? ? ? # 輸入賬號

? ? ? ? username = "$('#input1').val('上海-悠悠')"

? ? ? ? driver.execute_script(username)

? ? ? # 清空文本

? ? ? # time.sleep(5)

? ? ? # clear = "$('#input1').val('')"

? ? ? # driver.execute_script(clear)

? ? ? # 輸入密碼

? ? ? ? psw = "$('#input2').val('yoyo')"

? ? ? ? driver.execute_script(psw)

? ? ? # 點擊登錄按鈕

? ? ? ? button = "$('#signin').click()"

? ? ? ? driver.execute_script(button)

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末刁愿,一起剝皮案震驚了整個濱河市绰寞,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌铣口,老刑警劉巖滤钱,帶你破解...
    沈念sama閱讀 211,376評論 6 491
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異脑题,居然都是意外死亡仇味,警方通過查閱死者的電腦和手機阐污,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 90,126評論 2 385
  • 文/潘曉璐 我一進店門归园,熙熙樓的掌柜王于貴愁眉苦臉地迎上來亭枷,“玉大人,你說我怎么就攤上這事掏熬∮映恚” “怎么了?”我有些...
    開封第一講書人閱讀 156,966評論 0 347
  • 文/不壞的土叔 我叫張陵旗芬,是天一觀的道長舌胶。 經(jīng)常有香客問我,道長疮丛,這世上最難降的妖魔是什么幔嫂? 我笑而不...
    開封第一講書人閱讀 56,432評論 1 283
  • 正文 為了忘掉前任,我火速辦了婚禮誊薄,結(jié)果婚禮上履恩,老公的妹妹穿的比我還像新娘。我一直安慰自己呢蔫,他們只是感情好切心,可當我...
    茶點故事閱讀 65,519評論 6 385
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著片吊,像睡著了一般绽昏。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上俏脊,一...
    開封第一講書人閱讀 49,792評論 1 290
  • 那天全谤,我揣著相機與錄音,去河邊找鬼爷贫。 笑死认然,一個胖子當著我的面吹牛补憾,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播季眷,決...
    沈念sama閱讀 38,933評論 3 406
  • 文/蒼蘭香墨 我猛地睜開眼余蟹,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了子刮?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 37,701評論 0 266
  • 序言:老撾萬榮一對情侶失蹤窑睁,失蹤者是張志新(化名)和其女友劉穎挺峡,沒想到半個月后,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體担钮,經(jīng)...
    沈念sama閱讀 44,143評論 1 303
  • 正文 獨居荒郊野嶺守林人離奇死亡橱赠,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 36,488評論 2 327
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了箫津。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片狭姨。...
    茶點故事閱讀 38,626評論 1 340
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖苏遥,靈堂內(nèi)的尸體忽然破棺而出饼拍,到底是詐尸還是另有隱情,我是刑警寧澤田炭,帶...
    沈念sama閱讀 34,292評論 4 329
  • 正文 年R本政府宣布师抄,位于F島的核電站,受9級特大地震影響教硫,放射性物質(zhì)發(fā)生泄漏叨吮。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 39,896評論 3 313
  • 文/蒙蒙 一瞬矩、第九天 我趴在偏房一處隱蔽的房頂上張望茶鉴。 院中可真熱鬧,春花似錦景用、人聲如沸涵叮。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,742評論 0 21
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽围肥。三九已至,卻和暖如春蜂怎,著一層夾襖步出監(jiān)牢的瞬間穆刻,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 31,977評論 1 265
  • 我被黑心中介騙來泰國打工杠步, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留氢伟,地道東北人榜轿。 一個月前我還...
    沈念sama閱讀 46,324評論 2 360
  • 正文 我出身青樓,卻偏偏與公主長得像朵锣,于是被迫代替她去往敵國和親谬盐。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 43,494評論 2 348