相信各位看官在用selenium時,會發現發送長字符時,一個字符一個字符在輸入,特別在使用chrome時,更加明顯。
如果你的網頁是要大量編輯的怎么處理呢?
一、send_keys機制
既然問題出來了,我看就先看看send_keys是怎么實現發送字符的,為什么這么慢呢?看看webdriver的源碼吧

def send_keys(self, *value): """Simulates typing into the element. :Args: - value - A string for typing, or setting form fields. For setting file inputs, this could be a local file path. Use this to send simple key events or to fill out form fields:: form_textfield = driver.find_element_by_name('username') form_textfield.send_keys("admin") This can also be used to set file inputs. :: file_input = driver.find_element_by_name('profilePic') file_input.send_keys("path/to/profilepic.gif") # Generally it's better to wrap the file path in one of the methods # in os.path to return the actual path to support cross OS testing. # file_input.send_keys(os.path.abspath("path/to/profilepic.gif")) """ # transfer file to another machine only if remote driver is used # the same behaviour as for java binding if self.parent._is_remote: local_file = self.parent.file_detector.is_local_file(*value) if local_file is not None: value = self._upload(local_file) self._execute(Command.SEND_KEYS_TO_ELEMENT, {'value': keys_to_typing(value)})

def keys_to_typing(value): """Processes the values that will be typed in the element.""" typing = [] for val in value: if isinstance(val, Keys): typing.append(val) elif isinstance(val, int): val = str(val) for i in range(len(val)): typing.append(val[i]) else: for i in range(len(val)): typing.append(val[i]) return typing
從代碼中看,好像沒什么問題,append后再發送。
那么,很有可能就是對應瀏覽器的driver的問題導致的,看看官網,果然,在chromium中有一個相關的bug:https://bugs.chromium.org/p/chromedriver/issues/detail?id=1797#c1
具體內容我們就不細究了
二、測試
很多同學也會說,我用send_keys不慢阿,那我們下面分別用firefox和chrome瀏覽器來做一個實驗,看看send_keys的效率
1)firefox 45.0.2
在baidu頁中分別發2,10,30,60,100,200個英文字符,再用簡單粗暴的發送后time.time()減去發送前的time.time()來計算時間
代碼就不帖了,直接上結果,如下
再畫個圖吧
從圖可以看出,時間會隨着字符數而對應增加
2)chrome 55
從兩種瀏覽器測試結果看,send_keys的時間都會隨着字符數而對應增加
三、解決方案
那邊,如果被測的網頁屬於大量輸入型的網頁,又不想把時間浪費在這,怎么處理呢?網上方法也很多,這里總結一下
1)將文本放入剪切版,然后再使用ctl + v 快速輸入,但如果在windows上執行,還要再裝win32的包,如果在linux上執行,就不知道要裝什么了。
這個方法網上一大把,各位自行去找吧
2)用javascript
如下:
js = 'document.getElementById("kw").value="jajj"'
dirver.execute_script(js)
再查看下時間為:0.013s,很快
3)用jquery
又有新問題了,要寫入的地方沒有ID,也不想用getElements方法來輸第幾個,怎么辦?就jquery,支持xpath類型,方法如下:
inputTest="$('input[id=kw]').val('%s')" % “jajj”
dirver.execute_script(inputTest)
再查看下時間為0.0130000114441,時間一樣
總結,以上方法基本可以覆蓋。
可能在過程中還會遇到問題,如:
(1)如果要輸入的框中帶有\n,字符串處理不方便,可以使用json方式讀出,再輸入
(2)有的框用.value后,沒反應,可以再用send_keys再輸入一個空格激活
還有的