Selenium2+python自動化18-載入Firefox配置

來源:互聯網
上載者:User

標籤:逸出字元   設定   斜杠   wrapper   mat   預設   com   down   orm   

前言
有小夥伴在用指令碼啟動瀏覽器時候發現原來下載的外掛程式不見了,無法用firebug在開啟的頁面上繼續定位頁面元素,調試起來不方便 。

載入瀏覽器配置,需要用FirefoxProfile(profile_directory)這個類來載入,

profile_directory既為瀏覽器設定檔的路徑地址

 

一、遇到問題

1.在使用指令碼開啟瀏覽器時候,發現右上方原來下載的外掛程式firebug不見了,到底去哪了呢?2.用指令碼去開啟瀏覽器時候,其實是重新開啟了一個進程,跟手動開啟瀏覽器不是一個進程。

所以沒主動載入外掛程式,不過selenium裡面其實提供了對應的方法去開啟,只是很少有人用到。

二、FirefoxProfile

1.要想瞭解selenium裡面API的用法,最好先看下相關的協助文檔開啟cmd視窗,

輸入如下資訊:
-》python

-》from selenium import webdriver

-》help(webdriver.FirefoxProfile)


Help on class FirefoxProfile in module

selenium.webdriver.firefox.firefox_profile:

class FirefoxProfile(builtin.object)
| Methods defined here:
|
| init(self, profile_directory=None)
| Initialises a new instance of a Firefox Profile
|
| :args:
| - profile_directory: Directory of profile that you want to use.
| This defaults to None and will create a new
| directory when object is created.

2.翻譯過來大概意思是說,這裡需要profile_directory這個設定檔路徑的參數

3.profile_directory=None,如果沒有路徑,預設為None,啟動的是一個新的,

有的話就載入指定的路徑。

三、profile_directory

1.問題來了:Firefox的設定檔地址如何找到呢?2.開啟Firefox點右上方設定>?(協助)>故障排除資訊>顯示檔案夾

3.開啟後把路徑複製下來就可以了:

C:\Users\xxx\AppData\Roaming\Mozilla\Firefox\Profiles\1x41j9of.default

 

四、啟動設定檔

1.由於檔案路徑存在字元:\ ,反斜線在代碼裡是逸出字元,這個有點代碼基礎的應該都知道。

不懂什麼叫逸出字元的,自己翻書補下基礎吧!

2.遇到逸出字元,為了不讓轉義,有兩種處理方式:

第一種:\ (前面再加一個反斜線)

第二種:r”\"(字串前面加r,使用字串原型)

 

五、參考代碼:

# coding=utf-8
from selenium import webdriver
# 設定檔地址
profile_directory = r‘C:\Users\xxx\AppData\Roaming\Mozilla\Firefox\Profiles\1x41j9of.default‘
# 載入配置配置
profile = webdriver.FirefoxProfile(profile_directory)
# 啟動瀏覽器配置
driver = webdriver.Firefox(profile)

 

本章很簡單,多加2行代碼而已,主要是弄清楚原理。

Selenium2+python自動化18-載入Firefox配置

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.