Search code examples
pythonexcelseleniumopenpyxldata-driven-tests

Selenium python not read data from excel after i add some new login data into the excel file


I am working on one project to do automation using selenium python. everything is working fine, But I have added one new python file and added one URL, login ID, and password into the excel sheet. when I try to read data from excel it will through the error for newly added line. it will work perfectly for before added data. I have attached a video so you can get a better idea. Please check it.here

When I add new data and try to use it in my test it will send me an error only for newly added data.

FilePath = "C:/Users/Administrator/PycharmProject/LegrandPython/TestData/Data.xlsx"
datafile = load_workbook(FilePath)
datasheet = datafile.get_sheet_by_name('Test Data')
loginSheet = datafile.get_sheet_by_name("Login Credentials")

@pytest.fixture()
def MasterLogin(setup):
    driver = setup
    driver.get(loginSheet.cell(7, 2).value)
    driver.implicitly_wait(5)
    login = LoginScreen(driver)
    login.SetUsername(loginSheet.cell(8, 3).value)
    login.SetPassword(loginSheet.cell(8, 4).value)
    login.SignIn()
    driver.implicitly_wait(10)

@pytest.fixture()
def PracticeLogin(setup):
    driver = setup
    driver.get(loginSheet.cell(2, 2).value)
    driver.implicitly_wait(5)
    login = LoginScreen(driver)
    login.SetUsername(loginSheet.cell(2, 3).value)
    login.SetPassword(loginSheet.cell(2, 4).value)
    login.SignIn()
    driver.implicitly_wait(10)

This is the login function that I have created in my conftest.py file.

I get the error is:

test setup failed
setup = <selenium.webdriver.chrome.webdriver.WebDriver (session="cc10f542d67a8f2ca104628a1b92be8d")>

    @pytest.fixture()
    def MasterLogin(setup):
        driver = setup
>       driver.get(loginSheet.cell(8, 2).value)

conftest.py:36: 
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
..\..\LegrandPython\venv\lib\site-packages\selenium\webdriver\remote\webdriver.py:436: in get
    self.execute(Command.GET, {'url': url})
..\..\LegrandPython\venv\lib\site-packages\selenium\webdriver\remote\webdriver.py:424: in execute
    self.error_handler.check_response(response)
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _

self = <selenium.webdriver.remote.errorhandler.ErrorHandler object at 0x0000014CD53D03D0>
response = {'status': 400, 'value': '{"value":{"error":"invalid argument","message":"invalid argument: \'url\' must be a string\\...\n\\tRtlGetAppContainerNamedObjectPath [0x77427A9E+286]\\n\\tRtlGetAppContainerNamedObjectPath [0x77427A6E+238]\\n"}}'}

    def check_response(self, response: Dict[str, Any]) -> None:
        """
        Checks that a JSON response from the WebDriver does not have an error.
    
        :Args:
         - response - The JSON response from the WebDriver server as a dictionary
           object.
    
        :Raises: If the response contains an error message.
        """
        status = response.get('status', None)
        if not status or status == ErrorCode.SUCCESS:
            return
        value = None
        message = response.get("message", "")
        screen: str = response.get("screen", "")
        stacktrace = None
        if isinstance(status, int):
            value_json = response.get('value', None)
            if value_json and isinstance(value_json, str):
                import json
                try:
                    value = json.loads(value_json)
                    if len(value.keys()) == 1:
                        value = value['value']
                    status = value.get('error', None)
                    if not status:
                        status = value.get("status", ErrorCode.UNKNOWN_ERROR)
                        message = value.get("value") or value.get("message")
                        if not isinstance(message, str):
                            value = message
                            message = message.get('message')
                    else:
                        message = value.get('message', None)
                except ValueError:
                    pass
    
        
        if not value:
            value = response['value']
        if isinstance(value, str):
            raise exception_class(value)
        if message == "" and 'message' in value:
            message = value['message']
    
        screen = None  # type: ignore[assignment]
        if 'screen' in value:
            screen = value['screen']
    
        stacktrace = None
        st_value = value.get('stackTrace') or value.get('stacktrace')
        if st_value:
            if isinstance(st_value, str):
                stacktrace = st_value.split('\n')
            else:
                stacktrace = []
                try:
                    for frame in st_value:
                        line = self._value_or_default(frame, 'lineNumber', '')
                        file = self._value_or_default(frame, 'fileName', '<anonymous>')
                        if line:
                            file = "%s:%s" % (file, line)
                        meth = self._value_or_default(frame, 'methodName', '<anonymous>')
                        if 'className' in frame:
                            meth = "%s.%s" % (frame['className'], meth)
                        msg = "    at %s (%s)"
                        msg = msg % (meth, file)
                        stacktrace.append(msg)
                except TypeError:
                    pass
        if exception_class == UnexpectedAlertPresentException:
            alert_text = None
            if 'data' in value:
                alert_text = value['data'].get('text')
            elif 'alert' in value:
                alert_text = value['alert'].get('text')
            raise exception_class(message, screen, stacktrace, alert_text)  # type: ignore[call-arg]  # mypy is not smart enough here
>       raise exception_class(message, screen, stacktrace)
E       selenium.common.exceptions.InvalidArgumentException: Message: invalid argument: 'url' must be a string

..\..\LegrandPython\venv\lib\site-packages\selenium\webdriver\remote\errorhandler.py:247: InvalidArgumentException

How can I resolve this please help me if anyone can have an idea.


Solution

  • I tried to replicate some of your code, and I did succeed. Then I had seen in detail about your website. It seems like you are logging in as a patient and creating a record, but you are not logging off, and when you try to get master url, it is logging on to the same, perhaps. Otherwise, when I added the 'signout' for each url, its working good. Below is the code that I tried with (though there is no framework I have organized with it, just a raw code for trial)

    from selenium import webdriver
    from selenium.webdriver.common.by import By
    from webdriver_manager.chrome import ChromeDriverManager
    import time
    import openpyxl
    
    driver = webdriver.Chrome(ChromeDriverManager().install())
    driver.maximize_window()
    
    wb = openpyxl.load_workbook('pythonProject/lengranderx.xlsx')
    sheet = wb.active
    for rowno in range(2, sheet.max_row+1):
        url = sheet.cell(row=rowno, column=2).value
        print(url)
        userid = sheet.cell(row=rowno, column=3).value
        pw = sheet.cell(row=rowno, column=4).value
    
        driver.get(url)
        time.sleep(4)
        driver.find_element(By.XPATH, "//*[@name='email']").clear()
        driver.find_element(By.XPATH, "//*[@name='email']").send_keys(userid)
        driver.find_element(By.XPATH, "//*[@name='password']").click()
        driver.find_element(By.XPATH, "//*[@name='password']").send_keys(pw)
        driver.find_element(By.XPATH, "//*[@type='submit']").click()
        time.sleep(5)
        if 'patient' not in url:
            driver.find_element(By.XPATH, "//*[@class='fa fa-chevron-down']").click()
            driver.find_element(By.XPATH, "//*[text() = 'Sign Out']").click()
            time.sleep(1)
        else:
            driver.find_element(By.XPATH,"//*[contains(@class, 'chakra-button__icon')]").click()
            time.sleep(1)
            driver.find_element(By.XPATH, "//*[text() = 'Sign Out']").click()
            time.sleep(0.5)
            driver.find_element(By.XPATH, "//*[text()='Continue']").click()
            time.sleep(1)
    
    # the below block is to run as an independent
    iurl = sheet.cell(row=8, column=2).value
    iuid = sheet.cell(row=8, column=3).value
    ipw = sheet.cell(row=8, column=4).value
    
    driver.get(iurl)
    time.sleep(5)
    driver.find_element(By.XPATH, "//*[@name='email']").clear()
    driver.find_element(By.XPATH, "//*[@name='email']").send_keys(iuid)
    driver.find_element(By.XPATH, "//*[@name='password']").click()
    driver.find_element(By.XPATH, "//*[@name='password']").send_keys(ipw)
    driver.find_element(By.XPATH, "//*[@type='submit']").click()
    time.sleep(5)
    driver.find_element(By.XPATH, "//*[@class='fa fa-chevron-down']").click()
    driver.find_element(By.XPATH, "//*[text() = 'Sign Out']").click()
    

    P.S. I have first tried with 7 rows (which does not include the master url). After it succeeded, I added the 8th row as master url and then ran the code again.