Python: How can i input lines read from a text file into a variable

38 views Asked by At

I'm currently working on a python script to develop a automatic fill form bot. Only doing 1 site until i get the process down. As of the moment i have 2 options. Option 1 is to input the client data manually, the script then takes this data into a variable to use for send.keys in order to fill the form on the particular website. This is working fine. Now my problem is with Option 2. I'm trying to import lines read from a text file. Store that data as content. The attach each lines (content[0]) to a variable, then use that variable with the send.keys command to auto fill the form. For example, My text file contains this data:

John Doe 123 Test Street Test City

I want to be able to read each line individually and assign it content. Line 1 would be read as content0 Line 2 would be read as content1 Line 3 would be read as content2 So on and so forth.

Then i would assign this value to a variable. Example.

FirstName = (content[0])
Address = (content[1])
City = (content[2])

Then my goal is to take this and use it with the send.keys command, so my bot fills in the box with the corresponding data.

This is where i am stuck at. When the script open the web page and starts the auto fill nothing displays in the boxes. if i add str like this str content[0] then it fills in the box with "content[0]" instead of the variable i have content assigned too. My code below.

if inputchoice == '2':  

    file = open('info.txt', 'r')
    read_=file.read()

    Phoneinput = (content[0])
    FirstNameinput = (content[1])
    LastNameinput = (content[2])
    Addyinput = (content[3])
    Cityinput = (content[4])
    Stateinput = (content[5])
    Stateinput2 = (content[6])
    Zipinput = (content[7])
    Emailinput1 = (content[8])

web = webdriver.Chrome()
web.get('https://www.listyourself.net/ListYourself/listing.jsp')
time.sleep(2)

Phone1 = web.find_element("xpath",'/html/body/div/div[2]/div[2]/div[1]/form/div[1]/div[2]/input[1]')
Phone1.send_keys(str(Phoneinput))
1

There are 1 answers

6
chepner On

The line

read_=file.read()

reads the entire contents of the file into a single str value assigned to the variable read. You then try to access the non-existent variable contents with the assumption that contents is a list whose elements are the individual lines. Replace the call to file.read with

contents = file.readlines()

to make your assumption true.