How do I enter a list of text from a txt file to a variable in python?

0

Issue

activation = driver.find_element(By.XPATH, '//*[@id="__layout"]/div/aside/div/div[1]/section[1]/div[1]/div/div/form/div[2]/div/span')
code = driver.find_element(By.XPATH, '//*[@id="__layout"]/div/aside/div/div[1]/section[1]/div[1]/div/div/form/div/input')

list = open("C:\Users\infin\Desktop\List.txt", "r")

I want to enter a list of code from List.txt into code as long as activation is true and create a loop depending on how many elements the list has

For example, if the list has 5 codes, I want to see that if activation is true or not. If it is true, it will timeout for 120 seconds (I can do this part)
Then after 120 seconds, it will enter the codes from the list.txt to code

I am still learning python and I’m trying out different stuffs and learning new words in python

Solution

I don’t know if I understand your problem but if you have codes in separated lines then you can do

 all_codes = open("C:\\Users\\infin\\Desktop\\List.txt", "r").read().split('\n')

Better use \\ in path because \ is used for special chars like \n (new line), \t (tab), etc. – even in path – and single \ can make problem. OR use prefix r for raw string.

 all_codes = open(r"C:\Users\infin\Desktop\List.txt", "r").read().split('\n')

And next you need for-loop to get single code, send it to input and check result.

from selenium.webdriver.common.keys import Keys

for value in all_codes:
    code = driver.find_element_xpath('//*[@id="__layout"]//section[1]/div[1]//form/div/input')

    code.send_key(value)
    code.send_key(Keys.ENTER)

    activation = driver.find_element_xpath('//*[@id="__layout"]//section[1]//form/div[2]/div/span')

    if activation.text == '... some text ...':
        break # exit loop before end of codes

You may need to use again find_element in every loop because find_element gives reference to object in memory and when you put code then it may change HTML and element can be moved in different place in memory.

You could also try to find shorter xpath with // or with classes or ids

Answered By – furas

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave A Reply

Your email address will not be published.

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More