I have a problem in class inheritance in Python; maybe it's not related to inheritance, but I have no other idea. I'm working with selenium web-driver. Here's the code I use:
from selenium import webdriver
class UIInterface(object):
def __init__(self):
self.driver = webdriver.Ie()
self.driver.get('URL')
def parentMethod(self, itemClassName = ''):
allElements = self.getAllElements()
return [el for el in allElements if el.get_attribute('type') == 'checkbox']
def getAllElements(self):
return self.driver.find_elements_by_tag_name('input')
class InterfaceChild(UIInterface):
def __init__(self):
super(InterfaceChild, self).__init__()
def childMethod(self):
returnedList = self.parentMethod(itemClassName = 'SomeClassName')
for item in returnedList:
print item.get_attribute('innerHTML')
This code gives me an error for line returnedList = self.parentMethod(itemClassName = 'SomeClassName'); the error description is this:
(<type 'exceptions.AttributeError'>, AttributeError("'InterfaceChild' object has no attribute 'self'",), <traceback object at 0x000000000418E5C8>)
I thought it might be related to inheritance, so I tried to put parentMethod and getAllElements in the class InterfaceChild; same exception raised. Any idea about this??
EDIT 1:
This is the main method for making instance of classes:
if __name__ == '__main__':
ieInterface = InterfaceChild()
ieInterface.childMethod()
This is the complete stack-trace:
Traceback (most recent call last):
File "C:\Program Files\Eclipse\eclipse-jee-helios-win32\eclipse-jee-helios-win32\plugins\org.python.pydev_2.8.2.2013090511\pysrc\pydevd.py", line 1446, in <module>
debugger.run(setup['file'], None, None)
File "C:\Program Files\Eclipse\eclipse-jee-helios-win32\eclipse-jee-helios-win32\plugins\org.python.pydev_2.8.2.2013090511\pysrc\pydevd.py", line 1092, in run
pydev_imports.execfile(file, globals, locals) #execute the script
File "D:\workspace\testCode.py", line 133, in main
ieInterface.childMethod()
File "D:\workspace\testCode.py", line 33, in childMethod
returnedList = self.parentMethod(itemClassName = 'SomeClassName')
File "D:\workspace\testCode.py", line 45, in parentMethod
allElements = self.getAllElements()
AttributeError: 'InterfaceChild' object has no attribute 'self'
I installed selenium with pip under Python 2.7 and changed the code to use Chrome driver[1] instead and changed the checker to make sure there would be some input tags being found. full code below. I'm running the code on Mac OS X. it works just fine.
So I guess the issue here is not the code. (Windows is not a friend of Python, perhaps :).
from selenium import webdriver
class UIInterface(object):
def __init__(self):
self.driver = webdriver.Chrome()
self.driver.get('http://duckduckgo.com')
def parentMethod(self, itemClassName = ''):
allElements = self.getAllElements()
result = [el for el in allElements]
print('===', result)
return result
def getAllElements(self):
return self.driver.find_elements_by_tag_name('input')
class InterfaceChild(UIInterface):
def __init__(self):
super(InterfaceChild, self).__init__()
def childMethod(self):
returnedList = self.parentMethod(itemClassName = 'SomeClassName')
for item in returnedList:
print item.get_attribute('innerHTML')
if __name__ == '__main__':
ieInterface = InterfaceChild()
ieInterface.childMethod()
The output looks like:
('===', [<selenium.webdriver.remote.webelement.WebElement object at 0x10e145cd0>, <selenium.webdriver.remote.webelement.WebElement object at 0x10e145d10>, <selenium.webdriver.remote.webelement.WebElement object at 0x10e145d50>])
[1] http://chromedriver.storage.googleapis.com/index.html?path=2.9/
Related
I have multiple py files with unit tests specified for specific module.
I want to import these unittests to seperate py file and run them from there, but I have trouble getting it working.
example of one of the unittest:
from webdriver_manager.chrome import ChromeDriverManager
from to_import import acceptConsent, URL_poznavacky, URL_poznavacky_vikendy, URL_poznavacky_rodiny, URL_pobocky
import time
from selenium import webdriver
import unittest
class TestPobocky_D(unittest.TestCase):
def setup_method(self, method):
self.driver = webdriver.Chrome(ChromeDriverManager().install())
self.vars = {}
def teardown_method(self, method):
self.driver.quit()
def test_pobocky_D(self):
self.driver.get(URL_pobocky)
acceptConsent(self.driver)
self.driver.maximize_window()
time.sleep(2)
mapa = self.driver.find_element_by_xpath("//*[#class='leaflet-pane leaflet-tile-pane']") ## jen jeden element, no need to call find_elementS
mapaDisplayed = mapa.is_displayed()
assert mapaDisplayed == True
mapaKolecka = self.driver.find_elements_by_xpath("//*[#class='leaflet-marker-icon marker-cluster marker-cluster-medium leaflet-zoom-animated leaflet-interactive']")
y=0
for _ in mapaKolecka:
mapaKoleckaDisplayed = mapaKolecka[y].is_displayed()
y=y+1
print("mapa kolecka")
assert mapaKoleckaDisplayed == True
pobockaBoxiky = self.driver.find_elements_by_xpath("//*[#class='f_branch-header f_anchor']")
x=0
for _ in pobockaBoxiky:
pobockaBoxikyDisplay = pobockaBoxiky[x].is_displayed()
print("boxiky")
assert pobockaBoxikyDisplay == True
x=x+1
basicInfo = self.driver.find_elements_by_xpath("//*[#class='f_branch-basicInfo']")
a=0
for _ in basicInfo:
basicInfoDisplay = basicInfo[a].is_displayed()
print("basic info ")
assert basicInfoDisplay == True
a=a+1
I want to import the whole class TestPobocky_D to new file and run it in seperate py file. I tried following:
import unittest
from pobocky import TestPobocky_D
TestPobocky_D(unittest.TestCase)
that just gives me this error
"Traceback (most recent call last):
File "C:/Users/KDK/Desktop/Automation_Local_Deploy_PyCharm/starter_local.py", line 4, in <module>
TestPobocky_D(unittest.TestCase)
File "C:\Users\KDK\anaconda3\lib\unittest\case.py", line 433, in __init__
testMethod = getattr(self, methodName)
TypeError: getattr(): attribute name must be string"
Anyone who can help me with this please ? Or point me to the right direction how to go about this.
Thanks in advance for every response
Can you please try as below?
starttest.py
import unittest
from pobocky import TestPobocky_D
if __name__ == '__main__':
unittest.main(argv=[''],verbosity=2, exit=False)
Run the command "python -m unittest starttest.py"
I am writing my first Python Selenium page factory and am getting an error regarding my waits.
My code is as follows
Basepage Class
class Basepage():
browser = None
def __init__(self, browser):
self.browser = browser
self.base_url = config.url
def wait_for_element(self, *element):
WebDriverWait(self.browser, 10).until(
EC.presence_of_element_located(*element)
)
def click_element(self, *element):
self.browser.find_element(*element).click()
def find_element(self, *element):
self.browser.find_element(*element)
CreatePage Class
class CreatePage(Basepage):
def isat_createpage(self):
self.wait_for_element(*CreatePageLocators.add_computer_title)
text = self.find_element(*CreatePageLocators.add_computer_title).text
if text == "Add a computer":
return True
else:
return False
Behave Step
#then('the user will be navigated to "Create_Computer" page')
def step_impl(context):
page = CreatePage(context.browser)
assert page.isat_createpage(), "not at ADD Computer page"
Locator I am using for the item
class CreatePageLocators:
add_computer_title = (By.XPATH, "//*[#id=\"main\"]/h1")
I am getting the error
Scenario: User can open Create Computer screen # features/UI_Tests/Create.feature:8
Given A user has navigated to the BB_Test_Webpage # steps/Backbase_common_steps.py:6
And add a new computer is clicked # steps/Backbase_common_steps.py:11
Then the user will be navigated to "Create_Computer" page # steps/web_create_steps.py:5
Traceback (most recent call last):
File "c:\users\richard.cariven\python\lib\site-packages\behave\model.py", line 1329, in run
match.run(runner.context)
File "c:\users\richard.cariven\python\lib\site-packages\behave\matchers.py", line 98, in run
self.func(context, *args, **kwargs)
File "steps\web_create_steps.py", line 8, in step_impl
assert page.isat_createpage(), "not at ADD Computer page"
File "C:\Users\richard.cariven\Documents\Backbase_Test_RC\modules\pages\createpage.py", line 15, in isat_createpage
self.wait_for_element(*CreatePageLocators.add_computer_title)
File "C:\Users\richard.cariven\Documents\Backbase_Test_RC\modules\pages\basepage.py", line 23, in wait_for_element
EC.presence_of_element_located(*element)
TypeError: __init__() takes 2 positional arguments but 3 were given
I imagine I am doing something very simple wrong. But help greatly appreciated
If you check the error it is mentioned about positional arguments.
EC.presence_of_element_located(*element)
TypeError: init() takes 2 positional arguments but 3 were given
Change the following inside function like that add one more parenthesis.
def wait_for_element(self, *element):
WebDriverWait(self.browser, 10).until(
EC.presence_of_element_located((By.XPATH, "//*[#id='main']/h1")))
Hi when I tried to use this piece of code:
import media
toy_story = media.Movie("Toy Story","A story of a boy and his toys come to life","http://upload.wikimedia.org/wikipedia/en/1/13/Toy_Story.jpg","https://www,youtube.com/watch?v=vwyZH85NQC4")
print(toy_story.storyline)
The directory for media and this file is: C:\Users\Lukes\Desktop\media
The code for media is here:
class Movie():
def __init__(self, movie_title, movie_storyline, poster_image, trailer_youtube):
self.title = movie_title
self.storyline = movie_storyline
self.poster_image_url = poster_image
self.trailer_youtube_url = trailer_youtube
and whenever I try to run entertainment_center.py
it comes out with this:
Traceback (most recent call last):
File "C:/Users/Lukes/Desktop/media/entertainment_center.py", line 1, in <module>
import media
File "C:/Users/Lukes/Desktop/media\media.py", line 2
^
IndentationError: expected an indented block
The method __init__ is with the class scope. Indent it to consider that.
class Movie(object):
def __init__( self ):
self.id = 0
Plus, don't indent the top import instruction in the first file.
I am writing a script (headless browser) that loads a website and logs the time the resources of the website need to be loaded.
#!/usr/bin/env python
import gtk
import time
import webkit
import gobject
class Resource():
__signals = [
'content-length-received',
'load-failed',
'load-finished',
'response-received'
]
_start = time.time()
_durations = {}
def __init__(self, webkit_resource):
self._webkit_resource = webkit_resource
# literally copy the uri
self._uri = "".join([c for c in self._webkit_resource.get_uri()])
self._connect_callbacks()
#property
def uri(self):
return self._uri
def _connect_callbacks(self):
for s_id in self.__signals:
self._webkit_resource.connect(s_id, self._on_callback, s_id)
def _on_callback(self, *args):
self._durations[args[-1]] = time.time() - self._start
print "==>", self._uri, "==>", args[-1], "==>", self._durations[args[-1]]
class Browser(webkit.WebView):
def __init__(self):
webkit.WebView.__init__(self)
gobject.threads_init()
self.connect('resource-request-starting',
self._on_resource_request_starting)
def _on_resource_request_starting(self, view, frame, resource, request, response):
c_resource = Resource(resource)
if __name__ == "__main__":
browser = Browser()
browser.open("http://amazon.com/")
gtk.main()
The code runs fine but then suddenly I get the following weird Tracebacks.
==> http://amazon.com/ ==> content-length-received ==> 0.98512005806
==> http://www.amazon.com/ ==> content-length-received ==> 0.985180854797
==> http://z-ecx.images-amazon.com/images/G/01/browser-scripts/us-site-wide-css-beacon/site-wide-5659237078._V1_.css ==> content-length-received ==> 0.986252069473
==> http://z-ecx.images-amazon.com/images/G/01/browser-scripts/us-site-wide-css-beacon/site-wide-5659237078._V1_.css ==> content-length-received ==> 0.987208843231
==> http://z-ecx.images-amazon.com/images/G/01/browser-scripts/us-site-wide-css-beacon/site-wide-5659237078._V1_.css ==> load-finished ==> 0.999194860458
==>
Traceback (most recent call last):
File "test.py", line 37, in _on_callback
print "==>", self._uri, "==>", args[-1], "==>", self._durations[args[-1]]
AttributeError: Resource instance has no attribute '_uri'
==>
Traceback (most recent call last):
File "test.py", line 37, in _on_callback
print "==>", self._uri, "==>", args[-1], "==>", self._durations[args[-1]]
AttributeError: Resource instance has no attribute '_uri'
==>
I did set self._uri. I actually copy each char one by one.
Is it being deleted somewhere?
We are using the cocos2d framework to create a game. We're completely new to this framework, so we cannot get the director object to work as we are expecting. Here is our code skeleton:
from cocos.director import director
from cocos.layer import base_layers
import sys
import math
import os
import pyglet
import cocos
world_width = 1000
world_height = 1000
class NetworkMap(cocos.layer.ScrollableLayer):
def __init__(self, world_width, world_height):
self.world_width = world_width
self.world_height = world_height
super(NetworkMap, self).__init__()
bg = ColorLayer(170,170,0,255,width=500,height=500)
self.px_width = world_width
self.px_height = world_height
self.add(bg,z=0)
class TestScene(cocos.scene.Scene):
def __init__(self):
super(TestScene,self).__init__()
def on_enter():
director.push_handlers(self.on_cocos_resize)
super(TestScene, self).on_enter()
def on_cocos_resize(self, usable_width, usable_height):
self.f_refresh_marks()
def main():
scene = TestScene()
director.init(world_width, world_height, do_not_scale=True)
world_map = NetworkMap(world_width, world_height)
scroller = cocos.layer.ScrollingManager()
scroller.add(world_map)
scene.add(scroller)
director.run(scene)
So for some reason the director doesn't have all the attributes we want.
Our stack trace is:
Traceback (most recent call last):
File "map.py", line 49, in <module>
main()
File "map.py", line 39, in main
scene = TestScene()
File "map.py", line 29, in __init__
super(TestScene,self).__init__()
File "/usr/local/lib/python2.7/dist-packages/cocos2d-0.5.5-py2.7.egg/cocos/scene.py", line 95, in __init__
super(Scene,self).__init__()
File "/usr/local/lib/python2.7/dist-packages/cocos2d-0.5.5-py2.7.egg/cocos/cocosnode.py", line 114, in __init__
self.camera = Camera()
File "/usr/local/lib/python2.7/dist-packages/cocos2d-0.5.5-py2.7.egg/cocos/camera.py", line 56, in __init__
self.restore()
File "/usr/local/lib/python2.7/dist-packages/cocos2d-0.5.5-py2.7.egg/cocos/camera.py", line 76, in restore
width, height = director.get_window_size()
File "/usr/local/lib/python2.7/dist-packages/cocos2d-0.5.5-py2.7.egg/cocos/director.py", line 522, in get_window_size
return ( self._window_virtual_width, self._window_virtual_height)
AttributeError: 'Director' object has no attribute '_window_virtual_width'
You need to initialise the director before you instantiate your first scene. The director is the global object that initialises your screen, sets up the Cocos2D framework, etc.
I found a few other errors:
You need to change ColorLayer to be fully qualified, e.g. cocos.layer.ColorLayer.
on_enter needs to have self as the first argument.
You need to define f_refresh_marks in your TestScene class.
Here's a working copy of the code. (Working, in the sense that it does not throw errors, not that it does any sort of scrolling.)
from cocos.director import director
from cocos.layer import base_layers
import sys
import math
import os
import pyglet
import cocos
world_width = 1000
world_height = 1000
class NetworkMap(cocos.layer.ScrollableLayer):
def __init__(self, world_width, world_height):
self.world_width = world_width
self.world_height = world_height
super(NetworkMap, self).__init__()
bg = cocos.layer.ColorLayer(170,170,0,255,width=500,height=500)
self.px_width = world_width
self.px_height = world_height
self.add(bg,z=0)
class TestScene(cocos.scene.Scene):
def __init__(self):
super(TestScene,self).__init__()
def on_enter(self):
director.push_handlers(self.on_cocos_resize)
super(TestScene, self).on_enter()
def on_cocos_resize(self, usable_width, usable_height):
self.f_refresh_marks()
def f_refresh_marks(self):
pass
def main():
director.init(world_width, world_height, do_not_scale=True)
scene = TestScene()
world_map = NetworkMap(world_width, world_height)
scroller = cocos.layer.ScrollingManager()
scroller.add(world_map)
scene.add(scroller)
director.run(scene)
if __name__ == '__main__': main()
I had the same issue (with a very similar stack trace) and it was because I was trying to create a layer before calling director.init(). Moving director.init() to earlier in the code fixed it for me.