chromedriver仿真模擬手機操作(selenium)

chrome開發(fā)者工具中有模擬手機端調(diào)試工具,不光為自動化測試省筆買手機的錢(-_-這個具體還是看情況),還能讓爬蟲顯得更真實,使用起來就像下圖這樣

iPhone 6 Plus.png
以下就是代碼實現(xiàn)的兩種方式

導(dǎo)入selenium相關(guān)庫
from selenium import webdriver
from selenium.webdriver.common.touch_actions import TouchActions # 用來模擬手機端操作
1、通過設(shè)置設(shè)備名稱實現(xiàn)

這種方式只支持chrome設(shè)備列表中已存在的設(shè)備,不過你也可以自己添加編輯

mobileEmulation = {'deviceName': 'Galaxy S5'}
options = webdriver.ChromeOptions()
options.add_experimental_option('mobileEmulation', mobileEmulation)
driver = webdriver.Chrome(chrome_options=options)
driver.get('http://m.baidu.com')
input('是否有效')
driver.close()
driver.quit()
2、通過自定義設(shè)備參數(shù)實現(xiàn)
WIDTH = 600
HEIGHT = 800
PIXEL_RATIO = 3.0
# UA 必須要是手機設(shè)備的
UA = 'Mozilla/5.0 (Linux; Android 4.1.1; GT-N7100 Build/JRO03C) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/35.0.1916.138 Mobile Safari/537.36 T7/6.3'
mobileEmulation = {"deviceMetrics": {"width": WIDTH, "height": HEIGHT, "pixelRatio": PIXEL_RATIO}, "userAgent": UA}
options = webdriver.ChromeOptions()
options.add_experimental_option('mobileEmulation', mobileEmulation)
driver = webdriver.Chrome(executable_path='chromedriver.exe', chrome_options=options)
driver.get('https://m.baidu.com')
time.sleep(1)
inputs = driver.find_element_by_xpath('//*[@id="index-kw"]')
TouchActions(driver).tap(inputs).perform() # 模擬觸控
input('是否有效')
driver.close()
driver.quit()
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容