python selenium環境搭建筆記

推薦一:《使用Python學習selenium測試工具》

推薦二:《selenium官方文檔》

  1. 安裝python(很簡單,網上很多教程)
  2. 安裝selenium
    • DOS窗口輸入:python -m pip install selenium
    • 查看安裝的selenium版本號
      • 打開命令行
      • 進入python環境,輸入:python
      • 導入selenium包:import selenium
      • 查看版本號:selenium.__version__
  3. 安裝chrome驅動
    • 下載chrome驅動
    • 解壓後把chromedriver.exe文件放到chrome安裝目錄裏
    • 把chrome安裝目錄的路徑配置到環境變量path中
  4. eclipse下的pydev安裝
    • 可以用其他編輯工具,pycharm等
  5. 驗證selenium是否安裝成功
# TestSelenium.py

#!/user/bin/env python
#encoding: utf-8

from selenium import webdriver

# 此處註釋的代碼可能出現調起firefox不能正常請求get地址
# 這裏要注意:selenium和firefox版本匹配
# 我這裏裝的是selenium 2.53.6 + firefox45.3
# 之前裝的firefox48.0執行時會有異常,羣友建議45.0以下
# 
# browser = webdriver.Firefox()
# browser.get(url="https://www.baidu.com")
# browser.close()

chrome_driver_path = r"C:\Program Files (x86)\Google\Chrome\Application\chromedriver.exe"
browser = webdriver.Chrome(chrome_driver_path)
browser.get("https://www.baidu.com")
print(browser.title)

browser.find_element_by_id("kw").send_keys("gg")
browser.find_element_by_id("su").click()

到這裏selenium基本環境已經搭建完成了。

  • 搭建過程中遇到個問題:

    • 未安裝chrome驅動時,直接用webdriver調起firefox,使用其get方法傳參時總是報錯;

      Traceback (most recent call last):
        File "E:\fish\phpWeb\eclipse\MyPydev\mysrc\test.py", line 7, in <module>
          browser.get("https://www.baidu.com")
      TypeError: get() missing 1 required positional argument: 'url'
    • webdriver文件中,關於get的定義:

      def get(self, url):
              """
              Loads a web page in the current browser session.
              """
              self.execute(Command.GET, {'url': url})
    • 不知道爲什麼錯誤提示需要傳兩個參數?另一個問題,這兩個參數應該怎麼傳,才能保證程序正常運行?
      • 經羣友指點,這裏定義的兩個參數,其實並不是說調用時要傳兩個
      • 這裏的self是python定義函數的一種默認形式,類似於java的this
      • 最後問題定位到:firefox瀏覽器版本不匹配 + 調用Firefox時,要加“()”
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章