Selenium筆記——可當做簡略教程使用哦

Selenium筆記——可當做簡略教程使用哦

Abstract

參見我的語雀,記得關注我哦:https://www.yuque.com/jhongtao/zr9a1x/msb6ct

Selenium with Python中文翻譯文檔:https://selenium-python-zh.readthedocs.io/en/latest/

測試教程網上的Selenium教程:http://www.testclass.net/selenium_python/

Github上的案例文檔:https://github.com/xuyichenmo/selenium-document

當然還有我的Selenium實戰啦:https://www.yuque.com/jhongtao/zr9a1x/fo15yt

創建瀏覽器對象driver

from selenium.webdriver import Firefox	# 從selenium中import firefox
from selenium.webdriver.firefox.options import Options	#導入 firefox.options

options = Options() # 創建Options對象
options.add_argument('-headless')   # 設置瀏覽的方式爲無界面方式,這樣可以加快爬蟲速度
# 我把geckodriver.exe文件放在了E:\ProgramFiles\firefox\geckodriver,根據實際情況修改executable_path參數值
driver = Firefox(executable_path=in_k.executable_path, firefox_options=options) # 創建driver瀏覽器對象

driver對象常用方法和屬性

driver.get(url)獲取網頁

driver.get(url)	#參數url爲需要爬取的網頁地址

driver.page_source獲取網頁源代碼

printf(driver.page_source)	# 打印網頁源代碼

獲取標籤中的文本內容

driver.find_element_by_id("id_name").text	# 通過網頁元素的id獲取標籤中的文本內容

driver.title獲取網頁的標題

print(driver.title)	#打印網頁的標題

driver.save_screenshout(“img_name.img”)保存當前網頁爲圖片

driver.save_screenshout("img_name.png")	# 將當前網頁的頁面效果保存爲png,img_name.png爲圖片文件的名稱

button.click()模你鼠標單擊事件

button = driver.find_element_by_id("id_name")	# 獲取id爲id_name的按鈕
button.click()	# 模你鼠標單擊事件

input.send_keys(u “keyword”)給輸入框添加內容

input = driver.find_element_by_id("id_name")	# 獲取頁面中id爲in_name的元素
keyword = "百度”	# 設置需要輸入的內容
input.send_keys(u keyword)	# 給input輸入框添加輸入內容keyword

element.send(Keys.value, ‘letter’)模你鍵盤操作

# 首先要引入Keys包
from selenium.webdriver.common import keys

# 模你Ctrl+A全選文本輸入框的內容
input = driver.find_element_by_id("id_name")	# 獲取頁面中id爲in_name的元素
input.send_keys(Keys.CONTROL,'a')	# Ctrl+A操作

# 模你Ctrl+X剪切操作
input.send_keys(Keys.CONTROL,'x')	#Ctrl+X操作

# 模你Ctrl+Enter操作
keyword = "百度”	# 設置需要輸入的內容
input.send_keys(u keyword)	# 給input輸入框添加輸入內容keyword
input.send_keys(Keys.RETURN)	# Keys.RETURN 模你Enter操作

input.clear()清除輸入框內容

input = driver.find_element_by_id("id_name")	# 獲取頁面中id爲in_name的元素
input.clear()	# 清除輸入框內容

driver.get_cookies()獲取當前頁面的Cookie

print(driver.get_cookies())	#獲取當前頁面的Cooke

driver.current_url獲取當前頁面的網址

print(driver.current_url)	# 打印當前網頁的地址

driver.close()關閉當前頁面

# 關閉當前頁面,當獲得頁面之後,需要關閉頁面,以減少內存開銷
# 如果當前瀏覽器只打開了一個頁面,會同時關閉到瀏覽器,也就是釋放掉driver對象
driver.close() 

driver.quit()關閉瀏覽器

driver.quit()	#當瀏覽器使用完畢後要記得關閉瀏覽器

driver對象的方法和屬性詳情

Element元素獲取

獲取方式的兩種形式

1.直接通過元素的屬性值獲取

2.通過By的方式獲取:必須導入**from **selenium.webdriver.common.by **import **By

# 通過id獲取頁面元素
<div id = "id_name"></div>
div = driver.find_element_by_id("id_name")
#By的方式
from  selenium.webdriver.common.by import By
div = driver.find_element(by = By.ID,value = "id_name")	#方式一
div = driver.find_element(By.ID,"id_name")	#形式二

# 通過name標籤獲取元素
<input name = "name" type = "text"/>
input = driver.find_element_by_name("name")

# 通過標籤名獲取元素
<iframe src "#"></iframe>
iframe = driver.find_element_by_tage_name("iframe")

# 通過XPanth來獲取頁面元素
<input type = "text" name = "example"/>
<INPUT type = "text" name = "other"/>
inputs = driver.find_element_by_xpath("//input")

# 通過鏈接文本獲取頁面元素
<a href="#">百度</a>
baidu = drever.find_element_by_link_text("百度")

# 通過部分鏈接文本獲取頁面元素
<a href="#">baidu google sogou</a>
baidu = drever.find_element_by_link_text("google")

# 通過css樣式名稱來獲取頁面元素
# 類似於使用css的選擇器
<div id = "food">
	<span class = "dairy">milk</span>
    <span class = "dairy aged">cheese</span>
</div>
cheese = driver.find_element_by_css_selector("#food span.daiiri.aged")

ActionChains類 實現鼠標操作

# 非常重要使用之前必須先引入ActionChains類
from selenium.webdriver import ActionChains

# 鼠標移動到指定的元素
# 1.獲取指定的元素
button = driver.find_element_by_id("id_botton")	#獲取id爲id_name的按鈕元素
# 實現鼠標移動到button按鈕上
# 傳參:第一個參數爲driver對象,第二個參數爲元素對象
ActionChains(driver).move_to_element(button).perform()	

# 在元素位置單擊
# 參數說明:第一個參數爲driver對象,第二個參數和第三個參數都是需要點擊的元素對象
# 單擊操作邏輯:首先需要先獲取到元素,然後移動到元素上,最後在該元素上單擊
ActionChains(driver).move_to_element(button).click(button).perform()

# 在元素位置單擊並保持按住,與單擊類似
ActionChains(driver).move_to_element(button).click_and_hold(button).perform()

# 在元素位置雙擊,與單擊類似
ActionChains(driver).move_to_element(button).double_click(button).perform()

# 在元素位置右擊,與單擊類似
ActionChains(driver).move_to_element(button).context_click(button).perform()

# 將元素A移動到元素B的位置
e_a = driver.find_element_by_id("A")
e_b = driver.find_element_by_id("B")
ActionChains(driver).drag_and_drop(e_a,e_b).perform()

Select類 實現表單的填充

<select id = "status" >
	<option value = "0">北京</option>
	<option value = "1">上海</option>
	<option value = "2">深圳</option>
</select>

# 導入Select類
from selenium.webdriver.support.ui import Select

# 操作下拉列表
# 1.獲取下拉列表元素
select_element = driver.find_element_by_id("status")

# 2.創建Select對象,傳入初始化參數,也就是下拉列表元素
select = Select(select_element)

# 選擇下拉列表框的選項
select.select_by_index(0)	  	  # 根據索引選擇,index的值從0開始
select.select_by_value("1")		  #根據value值選擇
select.select_by_visible_text(u "深圳")	# 根據文字內容選擇

# 取消選擇
select.deselect_all()

switch_to_alert()方法 處理彈窗

alert = driver.switch_to_alert()	#獲取頁面彈窗

瀏覽器頁面切換

# 方法一:
driver.switch_to_window("window_name")	# 參數說明:window_name爲窗口的名稱

# 方法二:
# 通過使用window_handles()方法來獲取每個窗口的操作對象
for handle in driver.window_handles:
    driver.switch_to_window(handle)

頁面的前進和後退

# forward()實現前進操作
driver.forward()

# back()實現後退操作
driver.back()

獲取頁面Cookies

# 獲取頁面Cookie
for cookie in driver.get_cookies():
    prin(cookie['name'])
    
# 刪除Cookies
# 1.根據Cookies名稱刪除cookie
driver。delete_cookie("cookie_name")	#參數說明:cookie_name爲cookie的名稱

# 2.刪除頁面上的所有cookie
driver.delete_all_cookies()

頁面等待

隱式頁面等待

WebDriverWait類實現顯示等待

顯示等待指定某個條件,然後設置 最長等待時間,如果這個時間結束時還沒有找到元素,就會拋出異常

WebDriverWait(driver,timeout,poll_frequency=0.5,ignored_exceptions = None)
# 參數說明
# driver:WebDriver的瀏覽器驅動程序
# timeout:最長超時時間,默認以秒爲單位
# poll_frequency:休眠時間的間隔(步長),默認爲0.5s
# ignored_exceptions:超時後的異常信息,默認情況下拋出NoSuchElementException異常
# WebDriverWait對象一般與until()或者until_not()方法配合使用:
	使用這兩個函數的時候需要引入:expected_conditions
		from selenium.webdriver.support import expected_conditions as EC
    通過expected_conditions提供的參數程序爲until()或者until_not()提供參數
	until(EC.VALUE):調用該方法提供的驅動程序作爲一個參數,直到返回值不爲False
    until_not(EC.VALUE):調用該方法的驅動程序作爲一個參數,直到返回值爲False
    驅動程序參數列表:
    
# 實例
from selenium.webdriver import Firefox
from selenium.webdriver.firefox.options import Options
from  selenium.webdriver.common.by import By
# WebDriverWait庫,負責循環等待
from  selenium.webdriver.support.ui import WebDriverWait
# expected_conditions 負責條件出發
from selenium.webdriver.support import expected_conditions as EC

executable_path = "E:/ProgramFiles/firefox/geckodriver/geckodriver.exe"
url = "https://www.baidu.com/"
options = Options()  # 創建Options對象
options.add_argument('-headless')  # 設置瀏覽的方式爲無界面方式,這樣可以加快爬蟲速度
# 我把geckodriver.exe文件放在了E:\ProgramFiles\firefox\geckodriver,根據實際情況修改executable_path參數值
driver = Firefox(executable_path=executable_path, firefox_options=options)  # 創建driver瀏覽器對象
driver.get(url)
try:
    # 查找頁面輸入框 id = 'kw',知道找到了才返回,如果在10s內都沒有找到,則拋出異常
    input = WebDriverWait(driver,10).until(EC.presence_of_element_located((By.ID,'kw')))
finally:
    driver.quit()
    	

expected_conditions 驅動程序參數列表

class selenium.webdriver.support.expected_conditions.alert_is_present1

alert是否出現。

class selenium.webdriver.support.expected_conditions.element_located_selection_state_to_be(locator, is_selected)1

定位一個元素檢查的它的狀態是否和期待的一樣。locator是定位器,是(by,path)的元組,is_selected是布爾值。
class selenium.webdriver.support.expected_conditions.element_located_to_be_selected(locator)
定位的元素是否被選擇。

class selenium.webdriver.support.expected_conditions.element_selection_state_to_be(element, is_selected)1

定位一個元素檢查的它的狀態是否和期待的一樣。element是網頁元素,is_selected是布爾值。

class selenium.webdriver.support.expected_conditions.element_to_be_clickable(locator)1

元素是否是可見的或者是否是有效的,比如可以點擊。locator是定位器。

class selenium.webdriver.support.expected_conditions.element_to_be_selected(element)1

檢查元素是否是被選中的。element是網頁元素。

class selenium.webdriver.support.expected_conditions.frame_to_be_available_and_switch_to_it(locator)1

判斷該frame是否可以switch進去,如果可以的話,返回True並且switch進去,否則返回False。locator是定位器。

class selenium.webdriver.support.expected_conditions.invisibility_of_element_located(locator)1

檢查一個元素是否不可見或者在DOM中沒出現。locator是定位器。

class selenium.webdriver.support.expected_conditions.new_window_is_opened(current_handles)1

新的窗口是否打開,current_handles是當前窗口的句柄。

class selenium.webdriver.support.expected_conditions.number_of_windows_to_be(num_windows)1

打開的窗口是否滿足期待。

class selenium.webdriver.support.expected_conditions.presence_of_all_elements_located(locator)1

判斷網頁上是否存在至少一個定位的元素。locator是定位器。

class selenium.webdriver.support.expected_conditions.presence_of_element_located(locator)1

判斷元素是否存在DOM中,並不代表一定可見。locator是定位器。

class selenium.webdriver.support.expected_conditions.staleness_of(element)1

等待元素不再依附於DOM,即從DOM中刪除。如果在DOM中返回False,否則返回True。element是網頁元素。

class selenium.webdriver.support.expected_conditions.text_to_be_present_in_element(locator, text_)1

檢查元素中的文本內容是否存在指定的內容。locator是定位器。

class selenium.webdriver.support.expected_conditions.text_to_be_present_in_element_value(locator, text_)1

檢查元素的value值中是否存在指定的內容。locator是定位器。

class selenium.webdriver.support.expected_conditions.title_contains(title)1

判斷當前頁面的title是否包含預期字符串。是就返回True,否則False。

class selenium.webdriver.support.expected_conditions.title_is(title)1

判斷當前頁面的title是否精確等於預期。是就返回True,否則False。

class selenium.webdriver.support.expected_conditions.visibility_of(element)1

檢查元素是否在DOM中可見,可見的意思是不僅是顯示出來了,而且還有大於0的寬和高。element是網頁元素。

class selenium.webdriver.support.expected_conditions.visibility_of_any_elements_located(locator)1

檢查網頁上至少存在一個可見的指定元素。locator是定位器。

class selenium.webdriver.support.expected_conditions.visibility_of_element_located(locator)1

檢查元素是否在DOM中可見,可見的意思是不僅是顯示出來了,而且還有大於0的寬和高。locator是定位器。

expected_conditions案例

#coding=utf-8
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.wait import WebDriverWait

base_url = "http://www.baidu.com"
driver = webdriver.Firefox()
driver.implicitly_wait(5)
'''隱式等待和顯示等待都存在時,超時時間取二者中較大的'''
locator = (By.ID,'kw')
driver.get(base_url)

WebDriverWait(driver,10).until(EC.title_is(u"百度一下,你就知道"))
'''判斷title,返回布爾值'''

WebDriverWait(driver,10).until(EC.title_contains(u"百度一下"))
'''判斷title,返回布爾值'''

WebDriverWait(driver,10).until(EC.presence_of_element_located((By.ID,'kw')))
'''判斷某個元素是否被加到了dom樹裏,並不代表該元素一定可見,如果定位到就返回WebElement'''

WebDriverWait(driver,10).until(EC.visibility_of_element_located((By.ID,'su')))
'''判斷某個元素是否被添加到了dom裏並且可見,可見代表元素可顯示且寬和高都大於0'''

WebDriverWait(driver,10).until(EC.visibility_of(driver.find_element(by=By.ID,value='kw')))
'''判斷元素是否可見,如果可見就返回這個元素'''

WebDriverWait(driver,10).until(EC.presence_of_all_elements_located((By.CSS_SELECTOR,'.mnav')))
'''判斷是否至少有1個元素存在於dom樹中,如果定位到就返回列表'''

WebDriverWait(driver,10).until(EC.visibility_of_any_elements_located((By.CSS_SELECTOR,'.mnav')))
'''判斷是否至少有一個元素在頁面中可見,如果定位到就返回列表'''

WebDriverWait(driver,10).until(EC.text_to_be_present_in_element((By.XPATH,"//*[@id='u1']/a[8]"),u'設置'))
'''判斷指定的元素中是否包含了預期的字符串,返回布爾值'''

WebDriverWait(driver,10).until(EC.text_to_be_present_in_element_value((By.CSS_SELECTOR,'#su'),u'百度一下'))
'''判斷指定元素的屬性值中是否包含了預期的字符串,返回布爾值'''

#WebDriverWait(driver,10).until(EC.frame_to_be_available_and_switch_to_it(locator))
'''判斷該frame是否可以switch進去,如果可以的話,返回True並且switch進去,否則返回False'''
#注意這裏並沒有一個frame可以切換進去

WebDriverWait(driver,10).until(EC.invisibility_of_element_located((By.CSS_SELECTOR,'#swfEveryCookieWrap')))
'''判斷某個元素在是否存在於dom或不可見,如果可見返回False,不可見返回這個元素'''
#注意#swfEveryCookieWrap在此頁面中是一個隱藏的元素

WebDriverWait(driver,10).until(EC.element_to_be_clickable((By.XPATH,"//*[@id='u1']/a[8]"))).click()
'''判斷某個元素中是否可見並且是enable的,代表可點擊'''
driver.find_element_by_xpath("//*[@id='wrapper']/div[6]/a[1]").click()
#WebDriverWait(driver,10).until(EC.element_to_be_clickable((By.XPATH,"//*[@id='wrapper']/div[6]/a[1]"))).click()

#WebDriverWait(driver,10).until(EC.staleness_of(driver.find_element(By.ID,'su')))
'''等待某個元素從dom樹中移除'''
#這裏沒有找到合適的例子

WebDriverWait(driver,10).until(EC.element_to_be_selected(driver.find_element(By.XPATH,"//*[@id='nr']/option[1]")))
'''判斷某個元素是否被選中了,一般用在下拉列表'''

WebDriverWait(driver,10).until(EC.element_selection_state_to_be(driver.find_element(By.XPATH,"//*[@id='nr']/option[1]"),True))
'''判斷某個元素的選中狀態是否符合預期'''

WebDriverWait(driver,10).until(EC.element_located_selection_state_to_be((By.XPATH,"//*[@id='nr']/option[1]"),True))
'''判斷某個元素的選中狀態是否符合預期'''
driver.find_element_by_xpath(".//*[@id='gxszButton']/a[1]").click()

instance = WebDriverWait(driver,10).until(EC.alert_is_present())
'''判斷頁面上是否存在alert,如果有就切換到alert並返回alert的內容'''
print instance.text
instance.accept()

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