Switching between browser tabs - Appium - python-3.x

# get current window handle
window_before = self.driver.window_handles[0]
# click on a button which opens a new tab
self.driver.find_element(*EditLocators.preview_button).click()
# wait for new tab to open
self.wait_for_new_tab()
# get the new tab's window handle
window_after = self.driver.window_handles[1]
# switch to new tab
self.driver.switch_to.window(window_after)
"do some actions in new tab"
# close that new tab
self.driver.close()
# switch back to original tab
self.driver.switch_to.window(window_before)
The above is a code snippet of my appium tests of a website in chrome browser, which is being run on a physical device(android). There is a button on web page which opens a new tab. I have to switch between these two tabs, but I am getting this error:
selenium.common.exceptions.WebDriverException: Message: unknown error: 'name' must be a string
(Session info: chrome=69.0.3497.100)
(Driver info: chromedriver=2.38.552522
(437e6fbedfa8762dec75e2c5b3ddb86763dc9dcb),platform=Linux 4.15.0-38-generic x86_64)
at this line:
self.driver.switch_to.window(window_after)
my appium server version is 1.8.1 and appium python client version is 0.28.
When I printed "window_before" and "window_after" variables the result is CDwindow-0 , CDWindow-1 respectively

Updating appium sever from 1.8.1 to 1.9.1 solved the problem

Related

python3 selenium4: Message: session not created: No matching capabilities found when trying to open Chrome

I am trying to open chrome using selenium following here
I have added the following
options = ChromeOptions()
path = "/usr/bin/chromedriver"
driver = webdriver.Chrome(executable_path=path, chrome_options=options )
driver.get('https://www.google.com')
When I check where chrome driver is located I get
whereis chromedriver
chromedriver: /usr/bin/chromedriver
Both chrome driver and chrome are same versions.
What is causing this error: Message: session not created: No matching capabilities found when trying to open Chrome

I don't see icon on macOS system tray with the executable generated by pyinstaller

I develop an application with an icon in the system tray of macOS but when I generate the executable with pyinstaller and I launch the application, the menu is well in the system tray but I do not see the icon, as if I had nothing.
I use PySide6 6.4.0.1, Python 3.10.7 and pyinstaller 5.6.1.
Here is the code for the system tray
app = QApplication()
main_window = MainWindow()
if not QSystemTrayIcon.isSystemTrayAvailable():
QMessageBox.critical(None, 'System Tray', 'System tray was not detected!')
sys.exit(1)
app.setQuitOnLastWindowClosed(False)
icon = QIcon('ressources/icon.jpg')
tray = QSystemTrayIcon()
tray.setIcon(icon)
tray.setVisible(True)
menu = QMenu()
action_hello = QAction('Hello World')
action_hello.triggered.connect(main_window.say_hello)
menu.addAction(action_hello)
action_exit = QAction('Exit')
action_exit.triggered.connect(app.exit)
menu.addAction(action_exit)
tray.setToolTip('Hello World app')
tray.setContextMenu(menu)
tray.show()
# Launch the app
app.exec()
I finally succeeded. I have found a part of the solution here!
It was necessary to add the icon in a resource file specific to Qt.
Here is a tutoriel to do that.
I have create a file icon.qrc :
<!DOCTYPE RCC><RCC version="1.0">
<qresource prefix="/">
<file>ressources/icon.ico</file>
</qresource>
</RCC>
Then, I have run the following commmand in cmd : pyside6-rcc icons.qrc -o rc_icons.py.
After, I
I imported the new file created rc_icons.py in hello.py : import rc_icons.py.
Finally, I have created my icon like this : icon = QIcon(QPixmap(":/ressources/icon.ico"))
Now, when I run the pyinstaller command and the executable, I see the icon on the system tray.

save document.cookie output in a file

skillshare-downloader says:
grab your cookie by typing:
document.cookie
Then it says:
Copy-paste cookie from developer console (without " if present) into example script.
Example:
from downloader import Downloader
cookie = """
ADD YOUR COOKIE HERE
"""
It adds an extra step.
Is there any way we can save document.cookie output to a file so that we can just read the cookie from the file instead of going to the console and type document.cookie and copy-paste the output?
I checked How to write console.log to a file instead. I also checked Python open browser and run javascript function. It suggests using Selenium or webbroser module. However, I am not sure how to approach this problem.
What can I do?
Assuming that you are using chrome:
Install selenium by running in a terminal pip install selenium
Install a chromedriver via a manager (It allows you to control chrome) by running in a terminal pip install webdriver-manager
Create a file example.py and paste this inside
#import the selenium webdriver and the chromedriver
from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager
from time import sleep
#trying to stop skillshare from detecting we a are a bot
options = webdriver.ChromeOptions()
options.add_argument('--disable-blink-features=AutomationControlled')
#create the instance of chrome
driver = webdriver.Chrome(ChromeDriverManager().install(),options=options)
#get command used to open an url
driver.get('https://www.skillshare.com/')
#login part
#press on sign in
driver.find_element_by_css_selector("a.button.alt-white-ghost.transparent.initialized").click()
#change email here
driver.find_element_by_name("email").send_keys("testmail#mail.com")
#change password here
driver.find_element_by_name("password").send_keys("fakepassword")
#wait a second
sleep(1)
#click on sign in
driver.find_element_by_xpath("//span[text()='Sign In']/parent::button").click()
#wait 3 seconds for the login
sleep(3)
#execute_script is used to execute the command in the browser console, using return here to store it in a variable
cookie = driver.execute_script('return document.cookie')
#python way of creating a file on the given path and write the cookie inside it
f = open("D:\cookie.txt", "w")
f.write(cookie)
f.close()
#closing the chrome instance
driver.close()
open a terminal and type python example.py and it will run the script

Codeceptjs - Headless chrome - stepByStepReport enabled - I.switchToNextTab() hangs when the new tab opens a PDF file

"codeceptjs": "^3.0.2"
"#wdio/selenium-standalone-service": "^6.8.0"
"webdriverio": "^6.8.0"
Sample code:
I.amOnPage("https://www.pdfpdf.com/samples.html");
I.click('//a[#href="samples/Sample2.PDF"]');
I.switchToNextTab();
I.closeCurrentTab();
When above code is run in normal mode (non-headless) with or without stepByStepReport enabled, it works fine.
When above code is run with headless mode and stepByStepReport enabled - it hangs at I.switchToNextTab()
Looks like it is not able to take screenshot here
I switch to next tab
ยป Screenshot has been saved to
<>\0002.png
But 0002.png is not found. We have files only till 0001.png
When the code is run with headless mode and stepByStepReport is disabled, then it works fine.
So problem seems to be with:
Headless + stepByStepReport enabled + Link opens a PDF file
Any thoughts or suggestions on this?
It looks like still not supported in headless mode: https://github.com/puppeteer/puppeteer/issues/1872

Robot Framework using Python 3.6.8 on Ubuntu 18.04.2 LTS docker container

I have been unable to find a good public image that runs Robot Framework using Python v3.x on Ubuntu v18.x. A colleague built an image and I'm using it as a base but My robot script is failing to connect to the site and I've been spinning my wheels for far too long. It's time to reach out to the community for assistance!
I have a simple robot framework script (see below) that connects to a site (chrome headless) and validates the title. It's working find on my Ubuntu workstation but when I run a docker container atop that workstation - it just fails to connect. Initially, I thought it was a plumbing issue but that isn't the case. Below are the steps that I've taken along with the robot code that works on my workstation but not the container:
Confirm connection is working from container:
curl -o /dev/null -s -w %{http_code} https://www.google.com (this returns a 200)
Ensure the versions of python3, pip3 and ubuntu are the same on my workstation and container
Ensure pip3 libraries are the same (except for a few that I know I don't need and yes, I know I have a couple more installed than what I need) - here is the list from a pip3 freeze command:
asn1crypto==0.24.0
certifi==2020.4.5.1
chardet==3.0.4
coverage==5.2
cryptography==2.1.4
decorator==4.4.2
idna==2.6
importlib-metadata==1.7.0
jsonpath-rw==1.4.0
jsonpath-rw-ext==1.2.2
keyring==10.6.0
keyrings.alt==3.0
pbr==5.4.5
pluggy==0.13.1
ply==3.11
py==1.9.0
pycrypto==2.6.1
pygobject==3.26.1
pyxdg==0.25
requests==2.23.0
robotframework==3.1.1
robotframework-jsonlibrary==0.3.1
robotframework-requests==0.7.0
robotframework-seleniumlibrary==4.1.0
SecretStorage==2.3.1
selenium==3.141.0
six==1.11.0
tox==3.0.0
urllib3==1.22
virtualenv==16.7.10
zipp==3.1.0
And now the robot script (again, works on my workstation, just not on the container)
*** Settings ***
Documentation
... Basic Test for Google.com in headless mode
Library Collections
Library DateTime
Library Dialogs
Library OperatingSystem
Library SeleniumLibrary
Library String
Library RequestsLibrary
Library JSONLibrary
Suite Setup Setup Environment and Open Browser
Suite Teardown Close All Browsers
*** Variables ***
${BROWSER} HeadlessChrome
${SITE_URL} https://www.google.com
*** Test Cases ***
Title Test
Title Should Be Google
*** Keywords ***
Open Chrome Browser To URL
[Documentation] Open Chrome browser and navigate to URL with browser options set
[Tags] open_chrome_browser
${browserOptions} Run Keyword If 'Headless' in '${BROWSER}' Set Headless Chrome Options
Create Webdriver Chrome chrome_options=${browserOptions}
Go To ${SITE_URL}
Maximize Browser Window
Browser timeout and speed
[Documentation]
... Set browser timeout and speed
Set Selenium Timeout 30s
Set Selenium Speed 0s
Set Headless Chrome Options
[Documentation]
... Set the Chrome options for running in headless mode. Restrictions do not apply to headless mode.
[Tags] headless_chrome_options
${chromeOptions} Evaluate sys.modules['selenium.webdriver'].ChromeOptions() sys
Call Method ${chromeOptions} add_argument test-type
Call Method ${chromeOptions} add_argument --headless
Call Method ${chromeOptions} add_argument --disable-extensions
Call Method ${chromeOptions} add_argument --disable-gpu
Call Method ${chromeOptions} add_argument --disable-dev-shm-usage
Call Method ${chromeOptions} add_argument --no-sandbox
[Return] ${chromeOptions}
Setup Environment and Open Browser
[Documentation]
... This keyword will establish the environment variables and open a browser
[Tags] simple_test
Open Chrome Browser To URL
Browser timeout and speed
After running robot -b debug.log testgoogle.robot the debug log shows this interesting bit:
20200820 11:40:53.410 - DEBUG - Traceback (most recent call last):
File "/usr/local/lib/python3.6/dist-packages/SeleniumLibrary/__init__.py", line 467, in run_keyword
return DynamicCore.run_keyword(self, name, args, kwargs)
File "/usr/local/lib/python3.6/dist-packages/SeleniumLibrary/base/robotlibcore.py", line 102, in run_keyword
return self.keywords[name](*args, **kwargs)
File "/usr/local/lib/python3.6/dist-packages/SeleniumLibrary/keywords/element.py", line 569, in click_link
self.find_element(locator, tag='link').click()
File "/usr/local/lib/python3.6/dist-packages/SeleniumLibrary/base/context.py", line 74, in find_element
return self.element_finder.find(locator, tag, True, required, parent)
File "/usr/local/lib/python3.6/dist-packages/SeleniumLibrary/locators/elementfinder.py", line 76, in find
% (element_type, locator))
20200820 11:40:53.410 - INFO - +--- END KW: SeleniumLibrary.Click Link (74)
20200820 11:40:53.410 - INFO - +-- END KW: LoginHandler.User Logout (75)
Any thoughts or suggestions on troubleshooting steps?
Thanks much!
I still have not been able to get this to work with the ChromeDriver direct, however, I was able to get this to work using selenium grid:
https://selenium-release.storage.googleapis.com/3.141/selenium-server-standalone-3.141.59.jar
I started a Hub (in a container) and then a node directly on the container running the test and it worked. I'm still working on building the container that runs the node (it's not working as a separate container though...I must need to add some configurations). Below is the robot framework test suite using a remote chrome driver:
*** Settings ***
Documentation
... This is a simple robot test to open a browser and check the title of a given website.
Library Collections
Library DateTime
Library Dialogs
Library OperatingSystem
Library SeleniumLibrary
Library String
Library RequestsLibrary
Suite Setup Setup Environment and Open Browser
Suite Teardown Close All Browsers
*** Variables ***
${BROWSER} HeadlessChrome
${SITE_URL} https://www.google.com
*** Test Cases ***
Title Test
Title Should Be Google
*** Keywords ***
Open Chrome Browser To URL
[Documentation] Open Chrome browser and navigate to URL with browser options set
[Tags] open_chrome_browser
${chromeOptions} Evaluate sys.modules['selenium.webdriver'].ChromeOptions() sys, selenium.webdriver
Call Method ${chromeOptions} add_argument --headless
${ws}= Set Variable window-size=1920, 1080
Call Method ${chromeOptions} add_argument ${ws}
Call Method ${chromeOptions} add_argument --disable-extensions
Call Method ${chromeOptions} add_argument --disable-gpu
Call Method ${chromeOptions} add_argument --disable-dev-shm-usage
Call Method ${chromeOptions} add_argument --ignore-certificate-errors
${remoteOptions}= Call Method ${chromeOptions} to_capabilities
Create Webdriver Remote command_executor=http://<IP ADDR OF HUB>:4444/wd/hub desired_capabilities=${remoteOptions}
Go To ${SITE_URL}
Maximize Browser Window
Browser timeout and speed
[Documentation]
... Set browser timeout and speed
Set Selenium Timeout 30s
Set Selenium Speed 0s
Setup Environment and Open Browser
[Documentation]
... This keyword will establish the environment variables and open a browser
[Tags] simple_test
Open Chrome Browser To URL
Browser timeout and speed
Now to figure out how to run the node in a container...
After a bit more research, I just used the public Selenium Grid 3 hub and nodes to solve my issue.
https://github.com/SeleniumHQ/docker-selenium/tree/selenium-3/Hub

Resources