3

'm not able to click on the element. The code without letting me to see the Exception jumping to Except Block. In Except block also first 2 lines after flow control is going to for c in range(sheet.ncols): for r in range(sheet.nrows): Here not able to find or click on the xpath. And the code output is Process finished with exit code 0

from selenium import webdriver
import time

from selenium.common.exceptions import NoSuchElementException
import xlrd
driver = webdriver.Chrome(r'chromedriver.exe')
driver.maximize_window()
driver.get('url')
driver.switch_to.frame('m')
emailElem = driver.find_element_by_xpath('//*[@id="log_main"]/input')

# emailElem=browser.find_element_by_id('l')
# emailElem=browser.find_element_by_name("id")
emailElem.send_keys('[email protected]')
# time.sleep(5)
passwordElem = driver.find_element_by_xpath('//*[@id="log_main"]/p[1]/input')
passwordElem.send_keys('#####')

passwd=passwordElem.find_element_by_xpath('//*[@id="log_main"]/p[2]/input').click()
driver.switch_to.parent_frame()
driver.switch_to.frame('topFrame')

driver.find_element_by_css_selector('.menu > ul:nth-child(1) > li:nth-child(7) > a:nth-child(1) > span:nth-child(1)').click()#Reports
driver.switch_to.parent_frame()
driver.switch_to.frame('ST_mainFrame')
driver.find_element_by_css_selector('div.menu_row:nth-child(16) > span:nth-child(3) > label:nth-child(2)').click() #FTO


driver.switch_to.frame('fto_details')
time.sleep(8)
driver.find_element_by_css_selector('html body table tbody tr td form table tbody tr td a img').click()#search





path = r'C:\Users\username\PycharmProjects\Python\WebScraping\Book2.xlsx'
workbook = xlrd.open_workbook(path)
sheet = workbook.sheet_by_index(0)


"""def check_exists_by_xpath(xpath):
    try:
        driver.find_element_by_xpath(xpath)
    except NoSuchElementException:
        return False

    return True
    """
for c in range(sheet.ncols):
    for r in range(sheet.nrows):
        st = (sheet.cell_value(r, c))
        try:
            if st == float(st):
                st_string = str(int(st))



                xpath = "//input[@value='Analyze' and contains(@onclick,'" + st_string + "')]"
                #cont = 0
                if driver.find_elements_by_xpath(xpath):
                    driver.find_element_by_xpath(xpath).click() #Here new window will open
                    handles = driver.window_handles
                    h = len(handles)#h=2

                    #print(handles)
                    for handle in range(1,h):
                    #for handle in range(h):

                        driver.switch_to.window(handles[handle])
                        #driver.find_element_by_xpath('/html/body/table/tbody/tr[4]/td/table/tbody/tr[9]/td[3]/input').click()
                        driver.find_element_by_css_selector('.t2').click()
                        #time.sleep(2)
                        #driver.close()

                        lst_window = driver.window_handles
                        h2 = len(lst_window) #h2=2
                        def check_exists_by_xpath(xpath):
                            try:
                                driver.find_element_by_xpath(xpath)
                            except NoSuchElementException:
                                return False
                            return True

                        for lst_handle in range(2,h2):
                        #for lst_handle in range(1,h2):
                            driver.switch_to.window(lst_window[lst_handle])
                            xpath2 = "//*[@id='create_button']"
                            xpath3="//*[@id='update_button']"
                            #css2 = '#create_button'
                            #css3 = '#update_button'
                            if check_exists_by_xpath(xpath2):
                                driver.find_element_by_xpath(xpath2).click()
                                #driver.close()

                            elif check_exists_by_xpath(xpath3):
                                driver.find_element_by_xpath(xpath3).click()
                                #driver.close()

                           #if driver.find_element_by_css_selector(css2):
                            #    driver.find_element_by_css_selector(css2).click()
                            #elif driver.find_element_by_css_selector(css3):
                             #   driver.find_element_by_css_selector(css3).click()

                            #if driver.find_element_by_xpath(xpath2) or driver.find_element_by_xpath(xpath3):
                             #   driver.find_element_by_xpath(xpath2 or xpath3).click()
                              #  driver.close()
                            #elif driver.find_element_by_xpath(xpath3):
                                #driver.find_element_by_xpath(xpath3).click()
                                #driver.close()





                #cont+=1
            #print(cont)



        #except ValueError:
        except Exception:
            if st == str(st):
                xpath = "//input[@value='Analyze' and contains(@onclick,'" + st + "')]"
                #cont1=0
                if driver.find_elements_by_xpath(xpath):
                    driver.find_element_by_xpath(xpath).click()  # Here new window will open
                    handles = driver.window_handles
                    h = len(handles)  # h=2

                    # print(handles)
                    for handle in range(1, h):
                        # for handle in range(h):

                        driver.switch_to.window(handles[handle])
                        driver.find_element_by_xpath('/html/body/table/tbody/tr[4]/td/table/tbody/tr[9]/td[3]/input').click()
                        #time.sleep(5)
                        #driver.close()

                        lst_window = driver.window_handles
                        h2 = len(lst_window)  # h2=2
                        def check_exists_by_xpath(xpath):
                            try:
                                driver.find_element_by_xpath(xpath)
                            except NoSuchElementException:
                                return False
                            return True
                        #for lst_handle in range(1, h2):
                        for lst_handle in range(2,h2):
                            driver.switch_to.window(lst_window[lst_handle])
                            xpath2 = "//*[@id='create_button']"
                            xpath3 = "//*[@id='update_button']"
                            if check_exists_by_xpath(xpath2):
                                driver.find_element_by_xpath(xpath2).click()
                                #driver.close()

                            elif check_exists_by_xpath(xpath3):
                                driver.find_element_by_xpath(xpath3).click()
                                #driver.close()


"""
                            if driver.find_element_by_xpath(xpath2):
                                driver.find_element_by_xpath(xpath2).click()
                                driver.close()
                            elif driver.find_element_by_xpath(xpath3):
                                driver.find_element_by_xpath(xpath3).click()
                                """

What's wrong with my code. In excel i've n number of values(rows) in that only for the first value code is executing successfully. Rest of the values picking up, but

xpath = "//input[@value='Analyze' and contains(@onclick,'" + st_string + "')]"
                #cont = 0
                if driver.find_elements_by_xpath(xpath):

After this code the control moving back Excel(for loop) and some some time it's throwing ValueError.

except Exception:
    if st == str(st):
        xpath = "//input[@value='Analyze' and contains(@onclick,'" + st + "')]"
        #cont1=0

Here throwing an exception as

Traceback (most recent call last): File "m.py", line 53, in <module> if st == float(st): ValueError: could not convert string to float: '23' During handling of the above exception, another exception occurred: Traceback (most recent call last):

Can anyone help me, Thanks.

20
  • Can you upload the full text of the error you are getting? I'm a little confused what exactly the problem is. Also, since you are having a problem with your xPath, could you upload the HTML or link to the URL? Finally, where is driver defined? For example if you are using Chrome you need to define the driver in this fashion: driver = webdriver.Chrome(executable_path="/path/to/binary/chromedriver"); Commented Mar 11, 2019 at 21:24
  • On a second inspection I'm confused what you are trying to do. Where are you opening the browser in the first place? Selenium functions, like finding things by xPath, need to have opened a web browser as that is the only thing with which selenium can interact. Commented Mar 11, 2019 at 22:58
  • On top of path some code is there which I can't share Commented Mar 11, 2019 at 23:21
  • In any case, I don't think it will be possible to debug your xPath without the full HTML, or URL of the page(s). Finally, could you paste the full text of the error(s) you are getting? Commented Mar 11, 2019 at 23:24
  • Didn't get any error. Process finished with exit code 0 Commented Mar 11, 2019 at 23:33

2 Answers 2

1

Given your latest comment, it seems that the second window (at least) will not contain at least one of "//*[@id='create_button']" or "//*[@id='update_button']". This being the case, in the following block of code,

if driver.find_element_by_xpath(xpath2):
    driver.find_element_by_xpath(xpath2).click()
    driver.close()
elif driver.find_element_by_xpath(xpath3):
    driver.find_element_by_xpath(xpath3).click()
    driver.close()

At least one of

if driver.find_element_by_xpath(xpath2):

or

elif driver.find_element_by_xpath(xpath3):

will throw an ElementNotFoundException sending you to your except block.

This is because executing driver.find_element_by_xpath() throws such an error any time that element is not located.

I'm not sure what you're trying to accomplish or what your pages look like so I don't know what fix to make, but this seems to be the cause of your problem. If you can provide more details on exactly what you're trying to do with this loop I might be able to suggest a fix.

On second thought, the following might work:

Add this import and function somewhere:

from selenium.common.exceptions import NoSuchElementException        
def check_exists_by_xpath(xpath):
try:
    webdriver.find_element_by_xpath(xpath)
except NoSuchElementException:
    return False
return True

Then, change your original if block to:

if check_exists_by_xpath(xpath2):
    driver.find_element_by_xpath(xpath2).click()
    driver.close()
elif check_exists_by_xpath(xpath3):
    driver.find_element_by_xpath(xpath3).click()
    driver.close()

EDIT This is pretty much what I was thinking. Does it help?

from selenium import webdriver
import time
from selenium.common.exceptions import NoSuchElementException
import xlrd

driver = webdriver.Chrome(r'C:\Users\tmou\PycharmProjects\Python\WebScraping\chromedriver.exe')
driver.maximize_window()
driver.get('https://www.stew.cyz.com/st/st_main.php')
driver.switch_to.frame('ST_mainFrame')
emailElem = driver.find_element_by_xpath('//*[@id="log_main"]/input')

# emailElem=browser.find_element_by_id('log_main')
# emailElem=browser.find_element_by_name("hpuser_id")
emailElem.send_keys('[email protected]')
# time.sleep(5)
passwordElem = driver.find_element_by_xpath('//*[@id="log_main"]/p[1]/input')
passwordElem.send_keys('********')
passwd = passwordElem.find_element_by_xpath('//*[@id="log_main"]/p[2]/input').click()
driver.switch_to.parent_frame()
driver.switch_to.frame('topFrame')

driver.find_element_by_css_selector(
'.menu > ul:nth-child(1) > li:nth-child(7) > a:nth-child(1) > span:nth-child(1)').click()  # Reports
driver.switch_to.parent_frame()
driver.switch_to.frame('ST_mainFrame')
driver.find_element_by_css_selector(
'div.menu_row:nth-child(16) > span:nth-child(3) > label:nth-child(2)').click()  # FTO

driver.switch_to.frame('fto_details')
time.sleep(8)
driver.find_element_by_css_selector('html body table tbody tr td form table tbody tr td a img').click()  # search


path = r'C:\Users\tmou\PycharmProjects\Python\WebScraping\Book2.xlsx'
workbook = xlrd.open_workbook(path)
sheet = workbook.sheet_by_index(0)

for c in range(sheet.ncols):
    for r in range(sheet.nrows):
    st = (sheet.cell_value(r, c))
    try:
        if st == float(st):
            st_string = str(int(st))
            xpath = "//input[@value='Analyze' and contains(@onclick,'" + st_string + "')]"
            # cont = 0
            if driver.find_elements_by_xpath(xpath):
                driver.find_element_by_xpath(xpath).click()  # Here new window will open
                handles = driver.window_handles
                h = len(handles)  # h=2

                # print(handles)
                for handle in range(1, h):
                    # for handle in range(h):

                    driver.switch_to.window(handles[handle])
                    driver.find_element_by_xpath(
                        '/html/body/table/tbody/tr[4]/td/table/tbody/tr[9]/td[3]/input').click()
                    time.sleep(2)
                    driver.close()

                    lst_window = driver.window_handles
                    h2 = len(lst_window)  # h2=3

                    def check_exists_by_xpath(xpath):
                        try:
                            webdriver.find_element_by_xpath(xpath)
                        except NoSuchElementException:
                            return False
                        return True

                    # for lst_handle in range(2,h2):
                    for lst_handle in range(1, h2):
                        driver.switch_to.window(lst_window[lst_handle])
                        xpath2 = '//*[@id="create_button"]'
                        xpath3 = '//*[@id="update_button"]'


                        if check_exists_by_xpath(xpath2):
                            driver.find_element_by_xpath(xpath2).click()
                            driver.close()
                        elif check_exists_by_xpath(xpath3):
                            driver.find_element_by_xpath(xpath3).click()
                            driver.close()

            # cont+=1
        # print(cont)



    # except ValueError:
    except Exception:
        if st == str(st):
            xpath = "//input[@value='Analyze' and contains(@onclick,'" + st + "')]"
            # cont1=0
            if driver.find_elements_by_xpath(xpath):
                driver.find_element_by_xpath(xpath).click()  # Here new window will open
                handles = driver.window_handles
                h = len(handles)  # h=2

                # print(handles)
                for handle in range(1, h):
                    # for handle in range(h):

                    driver.switch_to.window(
                        handles[handle])  # /html/body/table/tbody/tr[4]/td/table/tbody/tr[9]/td[3]/input
                    driver.find_element_by_xpath(
                        '/html/body/table/tbody/tr[4]/td/table/tbody/tr[9]/td[3]/input').click()
                    # time.sleep(5)
                    driver.close()

                    lst_window = driver.window_handles
                    h2 = len(lst_window)  # h2=2

                    for lst_handle in range(2, h2):
                        if driver.switch_to.window(lst_window[lst_handle]):
                            driver.find_element_by_xpath('//*[@id="create_button"]').click()
                            driver.close()
                        else:
                            driver.find_element_by_xpath('//*[@id="update_button"]').click()
                            driver.close()
Sign up to request clarification or add additional context in comments.

18 Comments

I'm confused about where to define check_exists_by_xpath(xpath) function. so posting my first half code also.
from selenium import webdriver import time from selenium.common.exceptions import NoSuchElementException import xlrd driver=webdriver.Chrome(r'C:\Users\tmou\PycharmProjects\Python\WebScraping\chromedriver.exe') driver.maximize_window() driver.get('xyz.comt/st/st_main.php') driver.switch_to.frame('ST_mainFrame') emailElem = driver.find_element_by_xpath('//*[@id="log_main"]/input') emailElem.send_keys('[email protected]')
passwordElem = driver.find_element_by_xpath('//*[@id="log_main"]/p[1]/input') passwordElem.send_keys('#####') passwd=passwordElem.find_element_by_xpath('//*[@id="log_main"]/p[2]/input').click() driver.switch_to.parent_frame() driver.switch_to.frame('topFrame') driver.find_element_by_css_selector('.menu > ul:nth-child(1) > li:nth-child(7) > a:nth-child(1) > span:nth-child(1)').click()#Reports driver.switch_to.parent_frame() driver.switch_to.frame('ST_mainFrame')
driver.find_element_by_css_selector('div.menu_row:nth-child(16) > span:nth-child(3) > label:nth-child(2)').click() #FTO driver.switch_to.frame('fto_details') driver.find_element_by_css_selector('html body table tbody tr td form table tbody tr td a img').click()#search
It should work if you define it right above the if check_exists_by_xpath(xpath2). You will want the import statement at the top of the file with the other ones. Could you please add that code to your question? It is really hard to read in comments like this.
|
0

It looks like your current problem is simply that you are trying to convert a string with alphabetic characters to a float which would need strictly numerical values. Whatever data is on your excel sheet cannot be converted to a number.

6 Comments

Excel contains the values like : 1615525 1652273 4C17461624 1649059 Xapth : xpath = "//input[@value='Analyze' and contains(@onclick,'" + st_string + "')]" will take strings only so i'm trying to convert them to string.
If you just want to convert them to string why don’t you simply use st_string = str(st)?
I think one place you do, but you also have ‘st == float(st)’ on line 53 which I believe causes your current error.
Yes, because Excel values are integers and strings when we use that excel in your code INTEGERS will be treated as FLOATS so i'm trying them to convert INT and then STR . Directly i convert to STRINGS but .0 will be there at the end which i don't want.
#C.Peck Have you check it now.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.