Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to set window size using phantomjs and selenium webdriver in Python?
We can set window size using PhantomJS and Selenium webdriver in Python. PhantomJS is a headless browser that allows automated testing without displaying a GUI. To work with PhantomJS, we create a driver object of the webdriver.PhantomJS class and pass the path to the phantomjs.exe driver file as a parameter.
To set the window size, we use the set_window_size method and pass the width and height dimensions as parameters. We can also retrieve the current window size using the get_window_size method.
Syntax
driver.set_window_size(width, height) print(driver.get_window_size())
Parameters
- width − The desired window width in pixels
- height − The desired window height in pixels
Example
Here's how to create a PhantomJS driver, set a custom window size, and verify the dimensions ?
from selenium import webdriver
# Set phantomjs.exe path
driver = webdriver.PhantomJS(executable_path="C:\phantomjs.exe")
# Maximize window initially
driver.maximize_window()
# Launch URL
driver.get("https://www.tutorialspoint.com/index.htm")
# Set new window size (width=800, height=880)
driver.set_window_size(800, 880)
# Obtain and print current window size
print(driver.get_window_size())
# Close the driver
driver.quit()
Output
{'width': 800, 'height': 880}
Key Points
- PhantomJS is deprecated − Consider using Chrome or Firefox in headless mode instead
- Window size affects rendering − Some responsive websites display differently based on window dimensions
- Always call quit() − This ensures proper cleanup of browser resources
Alternative: Using Chrome Headless
Since PhantomJS is deprecated, here's the modern approach using Chrome headless ?
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
# Configure Chrome options
chrome_options = Options()
chrome_options.add_argument("--headless")
chrome_options.add_argument("--window-size=800,880")
# Create Chrome driver
driver = webdriver.Chrome(options=chrome_options)
# Launch URL and get window size
driver.get("https://www.tutorialspoint.com/index.htm")
print(driver.get_window_size())
driver.quit()
Conclusion
Use set_window_size() to control browser dimensions in PhantomJS. However, since PhantomJS is deprecated, consider migrating to Chrome or Firefox headless mode for better performance and ongoing support.
