自動化測試框架Selenium的使用——安裝Selenium

我是幹勾魚發表於2018-09-18

轉載請註明出處:http://blog.csdn.net/dongdong9223/article/details/82761255
本文出自【我是幹勾魚的部落格

Ingredient:

1 Selenium是什麼

Selenium是一個自動化測試框架,廣泛的用於自動化測試領域(是不是真的廣泛用於自動化測試領域我也不知道,沒怎麼搞過自動化測試 -_-!,這是我臆測的 = ̄ω ̄=)。因為它能夠模擬人工操作,比如能在瀏覽器中點選按鈕、在輸入框中輸入文字、自動填充表單、還能進行瀏覽器視窗的切換、對彈出視窗進行操作。也就是說你能手動做的東西,基本都能用它來實現自動化!

2 安裝Selenium

在python3下安裝Selenium,使用命令:

pip3 install selenium

3 下載Chrome瀏覽器指定版本驅動

使用Selenium經常會在瀏覽器下使用,當然Chrome瀏覽器是較為常用的,經常Chrome中訪問網頁時會遇到如下錯誤:

selenium.common.exceptions.WebDriverException: Message: ‘chromedriver’ executable needs to be in PATH. Please see https://sites.google.com/a/chromium.org/chromedriver/home

其實這是因為沒有找到合適的Chrome驅動,解決辦法就是講chromedriver下載下來,並制定路徑,既可以指定到環境變數裡,也可以在selenium執行檔案中指定這裡採用後者。

先到chromedriver官網下載與你所安裝的Chrome瀏覽器版本相匹配的chromedriver,這裡注意,筆者Chrome瀏覽器版本是69,我們找到當前最新的chromedriver 2.42版本這裡,開啟note.txt檔案,檢視這個版本瀏覽器對應的chromedriver驅動,能夠看到:

----------ChromeDriver v2.42 (2018-09-13)----------
Supports Chrome v68-70
Resolved issue 2144: Test testClickElement from MobileEmulationCapabilityTest class fails on Chromium for all platforms [[Pri-1]]
Resolved issue 2566: whitelisted-ips not working with ipv4 [[Pri-1]]
Resolved issue 2541: chromedriver v2.41 fails to start with whitelisted-ips flag on macOS [[Pri-1]]
Resolved issue 2057: Set Timeouts is not implemented [[Pri-1]]
Resolved issue 1938: Take element screenshot not implemented in Chromedriver [[Pri-2]]
Resolved issue 2550: chromedriver ignores PATH when searching for chrome binary [[Pri-2]]
Resolved issue 1993: Fullscreen Window command not spec compliant [[Pri-2]]
Resolved issue 2501: Implement log-replay functionality [[Pri-2]]
Resolved issue 2552: Some error codes are not standard compliant [[Pri-2]]
Resolved issue 669: console.log with multiple arguments not handled properly [[Pri-2]]
Resolved issue 2545: Getting “unknown error: getting size failed to return x” for SVG rect [[Pri-2]]
Resolved issue 2571: chromedriver 2.35 ~ 2.41 - touch emulation not working (swipe) [[Pri-]]
----------ChromeDriver v2.41 (2018-07-27)----------
Supports Chrome v67-69
Resolved issue 2458: Chromedriver fails to start with whitelisted-ips option [[Pri-1]]
Resolved issue 2379: Returned capabilities should include remote debugging port [[Pri-2]]
Resolved issue 1005: driver.manage().window().getSize() is not implemented on Android [[Pri-2]]
Resolved issue 2474: desktop launcher error messages are not readable by users [[Pri-]]
Resolved issue 2496: Fail fast when not able to start binary [[Pri-]]
Resolved issue 1990: Close Window return value does not conform with spec [[Pri-]]
----------ChromeDriver v2.40 (2018-06-07)----------
Supports Chrome v66-68
Resolved issue 2446: Regression: Chromedriver 2.39 hangs on open when user-data-dir is specified and exists [[Pri-1]]
Resolved issue 779: Make ChromeDriver able to listen on requests from IPv6. [[Pri-1]]
Resolved issue 2339: Chromedriver couldn’t find the Android file using valid file path [[Pri-2]]
Resolved issue 2307: /session/:sessionId/send_command and /session/:sessionId/send_command_and_get_result should be changed to be proper extension commands [[Pri-]]

可知v2.41、v2.42都支援Chrome的69這個版本,我們下載chromedriver 2.41

然後在使用selenium時指定驅動儲存的路徑,例如:

#指定使用的瀏覽器,初始化webdriver
driver = webdriver.Chrome(executable_path='/Users/yuhaidong/studying/selenium/chromedriver')

就可以了,詳見下面測試中的程式碼。

4 測試

4.1 例項1

建立檔案:

seleniumtest.py

內容如下:

from selenium import webdriver  				#匯入Selenium的webdriver
from selenium.webdriver.common.keys import Keys	#匯入Keys

#指定使用的瀏覽器,初始化webdriver
driver = webdriver.Chrome(executable_path='/Users/username/studying/selenium/chromedriver')
#請求網頁地址
driver.get("http://www.python.org")
#看看Python關鍵字是否在網頁title中,如果在則繼續,如果不在,程式跳出。
assert "Python" in driver.title
#找到name為q的元素,這裡是個搜尋框
elem = driver.find_element_by_name("q")
#清空搜尋框中的內容
elem.clear()								
#在搜尋框中輸入pycon
elem.send_keys("pycon")
#相當於Enter鍵,提交
elem.send_keys(Keys.RETURN)
#如果當前頁面文字中有“No results found.”則程式跳出
assert "No results found." not in driver.page_source
#關閉webdriver
driver.close()  

注意到這裡面的:

driver = webdriver.Chrome(executable_path='/Users/username/studying/selenium/chromedriver')

就制定了chromedriver的存放路徑。

執行:

python3 seleniumtest.py

就能夠出現Chrome瀏覽器被開啟並進行搜尋然後關閉,如果覺得一閃而過可以將“driver.close() ”註釋掉再執行一下檢視結果。

4.2 例項2

新建檔案:

seleniumtest_unsplash.py

內容如下:

from selenium import webdriver  				#匯入Selenium的webdriver
from selenium.webdriver.common.keys import Keys	#匯入Keys
from bs4 import BeautifulSoup					#匯入BeautifulSoup模組
import time										#匯入time模組

#指定使用的瀏覽器,初始化webdriver
driver = webdriver.Chrome(executable_path='/Users/yuhaidong/studying/selenium/chromedriver')
#請求網頁地址
driver.get("https://www.unsplash.com")

# 設定下拉次數
times = 3
# 迴圈操作下拉過程
for i in range(times):
	print("---------開始執行第", str(i + 1),"次下拉操作---------")

	#執行JavaScript實現網頁下拉倒底部
	driver.execute_script("window.scrollTo(0, document.body.scrollHeight - 2000);")

	print("第", str(i + 1), "次下拉操作執行完畢!開始等待頁面載入...")

	# 等待10秒(時間可以根據自己的網速而定),頁面載入出來再執行下拉操作
	time.sleep(10)

all_a = BeautifulSoup(driver.page_source, 'html.parser').find_all('img', class_='_2zEKz')

print("img標籤的數量是:", len(all_a))

#關閉webdriver
driver.close()

這段程式碼實現了利用Selenium下拉瀏覽器以便展示出新圖片的效果。為了能在控制檯中輸出圖片的數量,這裡面還用到了BeautifulSoup。

參考

selenium:解決 ‘chromedriver’ executable needs to be in PATH 報錯 | session not created exception

Python爬蟲小白入門(四)PhatomJS+Selenium第一篇

chromedriver官網

相關文章