Created
March 21, 2016 10:42
-
-
Save eyalzek/92ad1ebc49b45ba4d5b7 to your computer and use it in GitHub Desktop.
python-selenium-webdriver
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# selenium webdriver API: http://selenium-python.readthedocs.org/api.html | |
import time | |
import json | |
import sys | |
from selenium import webdriver | |
from selenium.common import exceptions | |
class Webpage(object): | |
"""A headless PhantomJS page running the formular page""" | |
def __init__(self): | |
super(Webpage, self).__init__() | |
self.driver = webdriver.PhantomJS() | |
self.driver.set_window_size(1280, 720) | |
self.url = "https://google.com" # URL goes here | |
# flow logic can go here: | |
def run_flow(self): | |
self.driver.get(self.url) # navigate to url | |
self.print_title() # print page title | |
self.screenshot("homepage") # take a screenshot and name it homepage | |
# self.click_button(".className") # click css selector | |
def click_button(self, selector): | |
tag = self.wait_for_visibility(selector) | |
tag.click() | |
self.screenshot(selector) | |
self.print_title() | |
def wait_for_visibility(self, selector, timeout_seconds=5): | |
retries = timeout_seconds | |
pause_interval = 2 | |
while retries: | |
# print("tries left: {}".format(retries)) | |
try: | |
element = self.driver.find_element_by_css_selector(selector) | |
if element.is_displayed(): | |
return element | |
elif "visible" in element.value_of_css_property("visibility"): | |
print("trying to focus on element") | |
self.driver.execute_script("$(\"" + selector + "\").focus()") | |
except (exceptions.NoSuchElementException, | |
exceptions.StaleElementReferenceException): | |
if retries <= 0: | |
raise | |
else: | |
pass | |
retries = retries - 1 | |
time.sleep(pause_interval) | |
raise exceptions.ElementNotVisibleException( | |
"Element {} not visible despite waiting for {} seconds".format( | |
selector, timeout_seconds * pause_interval) | |
) | |
def print_title(self): | |
print("Page title:") | |
print(self.driver.title.encode('utf-8')) | |
def screenshot(self, filename): | |
print("saving %s" % filename) | |
self.driver.save_screenshot(filename + ".png") | |
def quit(self): | |
print("closing page...") | |
self.driver.quit() | |
def main(): | |
webpage = Webpage() | |
webpage.run_flow() | |
time.sleep(5) # sleep for 5 seconds | |
webpage.quit() | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment