在Python中通过Selenium打开Chrome浏览器的手机模式并进入开发者工具,可通过以下两种主要方式实现:
一、通过Chrome选项设置手机模式
-
启用开发者工具
使用
--auto-open-devtools-for-tabs
参数自动打开开发者工具,无需手动触发F12按键。 -
配置手机模式
通过
mobileEmulation
字典设置设备名称(如iPhone 6
、Galaxy S5
等),模拟手机屏幕尺寸和分辨率。
示例代码 :
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
import time
# 设置手机模式
mobile_emulation = {
"deviceName": "iPhone 6", # 或 "Galaxy S5" 等
"screenWidth": 375, # 苹果设备示例
"screenHeight": 667 # 苹果设备示例
}
# 配置Chrome选项
options = Options()
options.add_argument("--auto-open-devtools-for-tabs")
options.add_experimental_option("mobileEmulation", mobile_emulation)
# 启动浏览器
driver = webdriver.Chrome(options=options)
driver.get("https://www.baidu.com")
driver.maximize_window()
# 操作示例:输入文本
element = driver.find_element_by_id("index-kw")
element.send_keys("测试")
# 关闭浏览器
time.sleep(5)