'Resize Selenium browser window to emulate a phone screen
I want to be able to resize the Selenium browser window to emulate a phone screen that is small enough (340,695).
Is there a way to do that?
This is what I have so far, no luck:
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
EDIT: Answer below
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
Solution 1:[1]
Maybe using webdriver as a variable name for the webdriver is confusing. Try using
driver = webdriver.Chrome(executable_path=chromedriver_path)
And then you can resize window size with the following
driver.set_window_size(340, 695)
Solution 2:[2]
Working on a project right now, so had to find a way to do this. A smart solution to resize the window to match the device screen size:
driver.get("https://google.com") #Can be any website.
google_html = driver.find_element(By.TAG_NAME, "html")
width = google_html.value_of_css_property("width").rstrip("px")
height = google_html.value_of_css_property("height").rstrip("px")
driver.set_window_size(width, height)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Mate Mrše |
Solution 2 | Avel Yagudaev |