1. 程式人生 > 實用技巧 >瀏覽器模擬手機模式操作

瀏覽器模擬手機模式操作

程式碼實現如下:

import os
from  selenium import webdriver

#配置瀏覽器以手機模式啟動
chrome_options = webdriver.ChromeOptions()
#選擇一種存在的模式手機裝置(解析度)
chrome_options.add_experimental_option('mobileEmulation',{'deviceName':'iPhone X'})
print(type(chrome_options)) #import os
from  selenium import webdriver

#配置瀏覽器以手機模式啟動
chrome_options = webdriver.ChromeOptions()
#選擇一種存在的模式手機裝置(解析度) chrome_options.add_experimental_option('mobileEmulation',{'deviceName':'iPhone X'}) print(type(chrome_options)) #<class 'selenium.webdriver.chrome.options.Options'> print(chrome_options.to_capabilities()) #{'browserName': 'chrome', 'version': '', 'platform': 'ANY', 'goog:chromeOptions': {'mobileEmulation': {'deviceName': 'iPhone X'}, 'extensions': [], 'args': []}}
#將chrome_options:建立一個包含所有已設定選項和返回包含所有內容的詞典 new_new_chrome_options = chrome_options.to_capabilities() path= os.path.dirname(os.path.dirname(os.path.dirname(__file__))) executable_path = f'{path}/driver/chromedriver.exe' #建立一個driver driver = webdriver.Chrome(executable_path=executable_path,desired_capabilities=new_new_chrome_options) driver.get(
'http://www.baidu.com') driver.find_element_by_id('index-kw').send_keys('李白\n') driver.quit() print(chrome_options.to_capabilities()) #將chrome_options:建立一個包含所有已設定選項和返回包含所有內容的詞典 new_new_chrome_options = chrome_options.to_capabilities() path= os.path.dirname(os.path.dirname(os.path.dirname(__file__))) executable_path = f'{path}/driver/chromedriver.exe' #建立一個driver driver = webdriver.Chrome(executable_path=executable_path,desired_capabilities=new_new_chrome_options) driver.get('http://www.baidu.com') driver.find_element_by_id('index-kw').send_keys('李白\n') driver.quit()