首页 > 解决方案 > 调整 Selenium 浏览器窗口的大小以模拟手机屏幕

问题描述

我希望能够调整 Selenium 浏览器窗口的大小以模拟足够小 (340,695) 的手机屏幕。

有没有办法做到这一点?

这是我到目前为止所拥有的,没有运气:

from selenium.webdriver.common.keys import Keys
from time import sleep

chromedriver_path = '../chromedriver' # Change this to your own chromedriver path!
webdriver = webdriver.Chrome(executable_path=chromedriver_path)
webdriver.set_window_size(340,695) # Makes the chrome browser, mobile viewport
sleep(2)
webdriver.get('https://www.instagram.com/accounts/login/?source=auth_switcher') # Visit Instagram

编辑:下面回答

from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.action_chains import ActionChains

mobile_emulation = { "deviceName": "Pixel 2" }
opts = webdriver.ChromeOptions()
opts.add_experimental_option("mobileEmulation", mobile_emulation)

driver = webdriver.Chrome(executable_path=r"The path to your web driver",options=opts) #you must enter the path to your driver

标签: pythonselenium

解决方案


也许使用 webdriver 作为 webdriver 的变量名是令人困惑的。尝试使用

driver = webdriver.Chrome(executable_path=chromedriver_path)

然后您可以使用以下命令调整窗口大小

driver.set_window_size(340, 695)

推荐阅读