安裝使用Selenium with Python 進行自動化測試
阿新 • • 發佈:2018-12-11
1 安裝python
2 安裝Selenium
Python3.x安裝後就預設就會有pip(pip.exe預設在python的Scripts路徑下),使用pip安裝selenium:
pip install selenium
因我已安裝selenium,不可重複安裝。 可使用以下命令檢視是否安裝成功:
pip show selenium
3 安裝最新版谷歌和下載chromedriver
4 測試
- 1.helloworld
from selenium import webdriver browser = webdriver.Chrome() browser.get('http://www.baidu.com/')
第二行程式碼會開啟谷歌 第三行會開啟百度
#coding=utf-8 from selenium import webdriver import os import time # set little time stop and big time stop for viewing changes little_time_stop = 1 big_time_stop = 2 # 預設廣告條數 ads_num_require = 8 # 請求連線 req_url = "http://www.haosou.com/s?ie=utf-8&shb=1&src=360sou_newhome&q=%E9%B2%9C%E8%8A%B1" # 開啟瀏覽器 print ("Opening chrome ...") browser = webdriver.Chrome() # 開始請求 print ("Visit %s ..." %(req_url)) browser.get(req_url) # 獲取所有的廣告 print ("Get all advertisement ...") all_ads_li = browser.find_elements_by_css_selector('#e_idea_pp li') # 當前廣告條數 ads_num_current = len(all_ads_li) print ("Has been got %d ads" %(ads_num_current)) # 如果廣告條數與預設不符 if ads_num_current < ads_num_require: print ("The number of ads is not enough ( current : %d require: %d)" %(ads_num_current,ads_num_require)) # exit() # 獲取頂部連線 i = 0 for ads_li in all_ads_li: time.sleep(big_time_stop) i = i+1 print ("ads %d :" %i) try: main = ads_li.find_element_by_css_selector('h3 a') except: print ("\tError: ads %d cann't find" %(i)) else: print ("\tReady: visit ads %d" %(i)) main.click() print ("\tSucess: visit ads %d" %(i)) time.sleep(little_time_stop) try: img_link = ads_li.find_element_by_class_name('e_biyi_img') except: print ("\tError : no img in ads %d " %(i)) else: print ("\tReady : visit img_link %d" %(i)) img_link.click() print ("\tSuccess : visit img_link %d" %(i)) time.sleep(little_time_stop) try: child_div = ads_li.find_element_by_class_name('e_biyi_childLink'); except: print ("\tError : no child link in ads %d" %(i)) else: try: child_links = child_div.find_elements_by_css_selector('a') except: print ("\tError : find child_links error") else: num_links = len(child_links) print ("\tSuccess : there are %d child_links" %(num_links)) j = 0 for child_a in child_links: j = j + 1 print ("\t\tReady : visit child link %d in ads %d" %(j, i)) child_a.click() print ("\t\tSuccess : visit child link %d in ads %d" %(j, i)) time.sleep(little_time_stop) print ("End and thanks for your using!") # 下面程式碼選擇取消註釋 # 延時 # time.sleep(5) # 關閉當前視窗 # browser.close() # 關閉所有已經開啟的視窗 # browser.quit()
執行後