Friday, February 22, 2019

py0015: NameError: name 'Select' is not defined

Error 
select = Select(driver.find_element_by_id('id****')) 
NameError: name 'Select' is not defined

This error i received when i tried to select value from drop down menu while doing automation in python selenium

How ever i came to know that i was using correct code but some import class is missing from header of file. I need to add "from selenium.webdriver.support.select import Select" in main file or same file so that code will work fine.

Solution:
from selenium.webdriver.support.select import Select

Correct code for click on drop down:
select = Select(driver.find_element_by_id('**id**'))
select.select_by_visible_text('String')

Thursday, February 21, 2019

py0014: table_name1 = table_name.replace(',','') AttributeError: 'pyodbc.Row' object has no attribute 'replace'

Problem :
below is my sample code, where i am getting error table_name1 = table_name.replace(',','') AttributeError: 'pyodbc.Row' object has no attribute 'replace' and in same example you can cover how to use replace in python
    cursor.execute('select table_name from information_schema.tables')
    for table_name in cursor:
        table_name1 = table_name.replace(',','')
        print (table_name1)

I was trying to loop the list of all table names which are in schema using query "select table_name from information_schema.tables". The intention was to do some action based on the table exists or not.

Why i used replace:
suppose after for loop when i use command "print (table_name)", it gives output enclosed in single quotes and postfix by comma, so i used replace function to replace comma and it starts throwing above error.

Solution:
if you notice code above i gave "table_name" in for loop and for replace function we have to write it as str.replace(old,new). But in my case replace was not able to get any string in "table_name" because "table_name" is just act as "i" here in for loop and it is not a attribute in this situation.

So i have to use "table_name.table_name.replace(',','')"

Correct code as below:
    cursor.execute('select table_name from intermediate_table')
    for tb in cursor:

        table_name1 = tb.table_name.replace(',','')
        print (table_name1)

Here i have replace table_name in for loop with "tb" for better visibilty and better understanding.

Monday, February 18, 2019

py0013 : use function from another file in main file python

To make code convient and readable form it is neccessary to break code in multiple files, where you can write your code and write function can be later call on any where in the project. In python its easy to do.

Below is the sample code, i am taking the example from my previous post

py0012 : try catch in Python/ DB connection in try catch

which is having file name "file1" and t funcation made which will return something on db connection pass or fail and that can be used in mail file as per below code example. First we need to import file, then use funcation name directly "t()" without any file reference.


from file1 import *
if t() == "DBConnectionError":
    # your code will stop here, dependent file will not throw any error
exit(0)


if t() == 1:
# if database connection pass it will move further as per the written commands, this also show that how we can handle error on other files call
    driver = selenium.webdriver.Firefox(executable_path=FirefoxDriver, firefox_binary=binary, firefox_profile=profile)

py0012 : try catch in Python / DB connection in try catch

try catch is preliminary to add in your code, other wise if it break in between it looks ugly when error come to end user. To make code clean and show user friendly error you can use try catch, see one of the example below when database connection.

Earlier when database connection fails, it show red color unexpected error and since this file is being in use further so need to use try catch which will return something so that further can be used as if else for any type of condition

import os
import pyodbc
from configuration import *

try:
    crsrconn = pyodbc .connect("Driver={SQL Server Native Client 11.0};"
                                "Server="+ServerName+";"
                                "Database="+DatabaseName+";"
                                "Trusted_Connection=yes;"
                                "pwd="+Password+";")
    cursor = crsrconn.cursor()
    cursor.execute('SELECT count(*) rn FROM *****')
    for row in cursor:

        if row != 0:
            def t(): return 1
            print ('1')
        #else:
         #   def t(): return 0
          #  print ('0')

except pyodbc.Error as err:
    print("DBConnectionError")
    def t(): return ("DBConnectionError")

py0011 : Learnt Something impressive in Python

Code writing techniques

Today i tried to write some code in python like i used for , if , else, try, catch, return. By using this came to know python has some limitation, no we cant say limitation its syntax.


  • For "if" we can not keep the code below on same starting column point, you have to give "tab" space in front of them for any hierarchy .
  • write "return" like this, def t() return 1 or def t() return "true"

Thursday, February 14, 2019

py0010 : Firefox not opening Websites which are in Tunnel/Proxy

If your system has implemented with proxy or tunnel and you want to open a web link (which are in tunnel or in proxy)
note* generally these kind of websites not worked on internet, but the firefox leaunched by Selenium/python using Geckodriver is open with internet without any proxy setting given in your system. So you have add some lines of code in your .py file before Geckodriverr called so that it will open firefox with system proxy settings.

#Add proxy IP Address
proxy = "***.***.***.***"
#Add proxy port
port = int("****")

cap = DesiredCapabilities().FIREFOX
cap["marionette"] = True

profile = webdriver.FirefoxProfile()
profile.set_preference("network.proxy.type", 1)
profile.set_preference("network.proxy.http", proxy)
profile.set_preference("network.proxy.http_port", port)
profile.set_preference("network.proxy.ssl", proxy)
profile.set_preference("network.proxy.ssl_port", port)
profile.update_preferences()

Related/Helpful Links:
py0005 : selenium.common.exceptions.SessionNotCreatedException: Message: Unable to find a matching set of capabilities
py0004 : Begginner error, Open Firefox

py0009 : How to Declare Variable and Use variable in same file of Other file

Assume that i have two files in my project first is "__init__.py" another one is "configuration.py" and i am using config file for different type of parameters which needs to change timely. The case is declared variable in config file i have to access them in same file or different file in all project.
See below how this can be done.

Configuration.py :
FirefoxPath = "C:/Users/*****/AppData/Local/Mozilla Firefox/firefox.exe"
FirefoxDriver = "C:\\Users\\*****\\Desktop\\python\\geckodriver-v0.24.0-win64\\geckodriver.exe"


__init__.py :
import os
from Configuration import *
binary = FirefoxBinary(FirefoxPath)
driver = selenium.webdriver.Firefox(executable_path=FirefoxDriver, firefox_binary=binary, firefox_profile=profile)

Tuesday, February 12, 2019

py0008 : connection with sqlserver database

First of all you need to install pyodbc package if not you might face this error "unknown command pyodbc"

Open cmd and use below command to install :
pip install pyodbc

Helpfull Link :

py0003 : pip install selenium SyntaxError: invalid syntax, while install selenium


install above package. for me it is very easy step, to install this package connect with database without any error in single shot.

I used below code to connect with database.

import pyodbc
crsrconnection = pyodbc .connect("Driver={SQL Server Native Client 11.0};"
                      "Server=IPAddress Or Server Name\Instance;"
                      "Database=****;"
                      "Trusted_Connection=yes;pwd=****")


cursor = crsrconnection.cursor()
cursor.execute('SELECT count(*) rn FROM sametable')

for row in cursor:
    print(row)

py0007 : Click on div ul li span class "Display Name" Selenium Python

Being a startup its difficult to work around, but struggle of 2 days i was able to click on element having flow like div/ul/li/span/class.

Searched lot on google most of examples are with ID, but in my case id was not defined so i tried many time with class name and Display name with possible probability. At last able to Click.

Solution:
Add below lines in your code
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait as wait

wait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, "//span[text()='DisplayName']"))).click()



Wednesday, February 6, 2019

py0006 : selenium.common.exceptions.WebDriverException: Message: Failed to find firefox binary. You can set it by specifying the path to 'firefox_binary':

I have reinstalled the Firefox earlier it was working fine, suddenly it started giving this error. If you read error carefully it is going to search firefox.exe (binary file) which is unable to find.

Locate your firefox.exe file and set in a variable and add below lines in your code

from selenium.webdriver.firefox.firefox_binary import FirefoxBinary
binary = FirefoxBinary('C:/Users/****/AppData/Local/Mozilla Firefox/firefox.exe')
driver = selenium.webdriver.Firefox( firefox_binary=binary)

py0005 : selenium.common.exceptions.SessionNotCreatedException: Message: Unable to find a matching set of capabilities

Error : selenium.common.exceptions.SessionNotCreatedException: Message: Unable to find a matching set of capabilities

I am using latest Selenium 3.8.0 and GeckoDriver and Firefox version 64.0.2.
Below Firefox version 64.0.2 you might have set capability marionette to False using DesiredCapabilities

Solution
Add below code
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
cap = DesiredCapabilities().FIREFOX
cap["marionette"] = False

Tuesday, February 5, 2019

py0004 : Begginner error, Open Firefox

I have written the code and getting two type error from 3 rows of code that is ridiculous:
First error belongs to the Firefox driver which was not found and gives error like  "File "C:/Users/*****/Desktop/python/example/0001.py", line 3, in "

Second type of error is "NameError: name 'selenium' is not defined" as name showcase something not found related to selenium

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
driver = selenium.webdriver.Firefox()

Error on execution of code 
C:\Users\*****\AppData\Local\Programs\Python\Python37-32\python.exe C:/Users/*****/Desktop/python/example/0001.py
Traceback (most recent call last):
  File "C:/Users/*****/Desktop/python/example/0001.py", line 3, in
    driver = selenium.webdriver.Firefox()
NameError: name 'selenium' is not defined

Process finished with exit code 1


SOLUTION:
Add path for Firefox driver that you have downloaded from internet and add "Import selenium" at first line

import selenium
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
driver = selenium.webdriver.Firefox(executable_path= r'C:\\Users\\*****\\Desktop\\python\\geckodriver-v0.24.0-win64\\geckodriver.exe')

Run the Code, Firefox will open automatically

py0003 : pip install selenium SyntaxError: invalid syntax, while install selenium

I was trying to install python-selenium binding, somebody told me to execute below command but i was not aware where to execute, so while executing below command i was getting this error

>>> pip install selenium
  File "", line 1
    pip install selenium
              ^
SyntaxError: invalid syntax
>>> pip
Traceback (most recent call last):
  File "", line 1, in
NameError: name 'pip' is not defined

However i tried to search pip jar, but not found however able to find pip.exe file in installation folder of PYTHON. It was found at "C:\Users\*****\AppData\Local\Programs\Python\Python37-32\Scripts"

So now open CMD, move to above directory ( using cd batch command ) upto script (* it could be different in your case) and execute below command:


C:\Users\*****\AppData\Local\Programs\Python\Python37-32\Scripts>pip install selenium
Collecting selenium
  Downloading https://files.pythonhosted.org/packages/80/d6/4294f0b4bce4de0abf13e17190289f9d0613b0a44e5dd6a7f5ca98459853/selenium-3.141.0-py2.py3-none-any.whl (904kB)
    100% |████████████████████████████████| 911kB 3.9MB/s
Collecting urllib3 (from selenium)
  Downloading https://files.pythonhosted.org/packages/62/00/ee1d7de624db8ba7090d1226aebefab96a2c71cd5cfa7629d6ad3f61b79e/urllib3-1.24.1-py2.py3-none-any.whl (118kB)
    100% |████████████████████████████████| 122kB 3.6MB/s
Installing collected packages: urllib3, selenium
Successfully installed selenium-3.141.0 urllib3-1.24.1
You are using pip version 18.1, however version 19.0.1 is available.
You should consider upgrading via the 'python -m pip install --upgrade pip' command.

Friday, February 1, 2019

py0002 : No Python interpreter is selected

Error is too simple to understand.

This error generally come when you install some of the Python interface like Pycharm or Anaconda only and Python not have installed on your system.

Information for Starters - Python is command based language you need to open cmd and enter in python prompt.

But if you want to work more beautifully there are several interpreter in market to work on UI.

Solution for this problem - install Python.exe on your machine, use default installation process and any latest version of python, in my case i have installed "python-3.7.2.exe"

and launch PyCharm > after click on new project > Select interpreter and select "python.exe"

py0001 : could not find main class com/intellij/idea/main

Have you installed PyCharm on your system?
New to Python?

Probably there are chances of getting this error when trying to launch "JetBrains PyCharm Community Edition **** " from your desktop or from your start menu. I have search on google to reach out the solution every blog giving different solution related to Java_Home path, Java Version Issue ..etc..

But i simply uninstalled the application and installed as per below selection (see below screenshot)

While installation setup will ask for few Check boxes like 
  • 32-bit launcher
  • 64-bit launcher
  • Add lanchers dir to the PATH
  • Add "Open Folder as Project"
  • .py
  • Download and install JRE x64 by JetBrains

Earlier i have installed without "Download and install JRE x64 by JetBrains" selection so i was getting this error.

later i have uninstalled and re-install with all check-box selected with "32-bit launcher" and worked successfully.

Don't forgot to leave your comments if this is helpful.




web stats