Headless Chrome in Alibaba Cloud ECS

Browsing with Headless Chrome in Alibaba Cloud ECS.

Launch a new Instance of Elastic Compute Service (ECS).

Make sure python3 and pip3 are installed on this new instance.

And then run the following commands on terminal:
pip3 install selenium
apt-get install chromium-chromedriver


Save the following python code in file "headlessChrome.py"


import os
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

options = Options()
options.add_argument('--headless')
options.add_argument('--start-maximized')
options.add_argument("--start-fullscreen")
options.add_argument("--kiosk");
options.add_argument('--no-sandbox')
options.add_argument('--disable-dev-shm-usage')
options.binary_location = '/usr/bin/chromium-browser'

driver = webdriver.Chrome(executable_path='/usr/bin/chromedriver', options = options)
driver.set_window_size(1024, 800)
driver.maximize_window()

driver.get('https://www.google.com/')
driver.implicitly_wait(2) # seconds
driver.save_screenshot('screenshot.png')
driver.close()
driver.quit()
print('\nDone')


NOTE:
Change the path of chrome's binary if needed, by default it is at:
/usr/bin/chromium-browser

and also the path of chromedrive:
/usr/bin/chromedriver

And then run the above code with python3, on terminal run:
python3 headlessChrome.py

You will get the screenshot of the webpage "www.google.com"

You can now play with this and automate the functioning of browser.

For example, you can input text:
searchPhrase = 'Headless Chrome in Alibaba Cloud'
searchQuery = WebDriverWait(driver,10).until(EC.presence_of_element_located((By.XPATH,"//input[@name='q']")))
searchQuery.send_keys(searchPhrase)

and also click on any element of the web page:
driver.find_element_by_name("btnK").click()


For more details on selenium, visit the following link:
https://www.seleniumhq.org/projects/webdriver/

Comments