Home > front end >  Selenium Python - Grab information from text file and enter it onto a webpage
Selenium Python - Grab information from text file and enter it onto a webpage

Time:11-12

I have dabbled in python selenium for quite a while and I have hit a crossroads on something.

I want to grab information from a .txt file on my desktop and use the data within that .txt and write it onto a webpage. I know the basics of opening the .txt file and reading the file lines etc but I am struggling on getting it to write the text from the .txt document into the webpage.

For instance: "1" "2" "3"

^ Lets say those are the lines/text within the text file. I want it to grab "1" first and paste it into the text box on the page which I already have the xpath for. Then I want the script to restart do the page all over again but this time type "2" and keep repeating until there are no more lines in the .txt file. Hopefully that makes sense. If not please let me know and I will try to explain further, I looked online for a couple solutions but nothing really came close to what I wanted sadly. Thank you!

I got it to read the lines and print me what was in the text document but thats simple stuff and honestly havent learned that far ahead for what I need. Thats why I am hoping I can get a little guidance/help from here.

Example Below.

driver=webdriver.Chrome(r"C:\ProgramFile(x86)\ChromeDriver\chromedriver.exe)
driver.get('examplewebpage')

file = open(r'C:\Users\example\Desktop\test.txt','r')
read = file.readlines()
modified = []

for line in read:
    if line not in modified:
        modified.append(line.strip())
print(modified)
time.sleep(1)

n = driver.find_element(By.XPATH, '//*[@id="exampletextbox"]')
file = open(r'C:\Users\example\Desktop\test.txt','r')
lines = file.readlines()
for line in lines:
    n = driver.find_element(By.XPATH, '//*[@id="exampletextbox"]')
    n.send_keys(line.strip())  
file.close()

CodePudding user response:

The solution will look like this:

from selenium import webdriver
from selenium.webdriver.common.by import By
from time import sleep


with open('myfile.txt', 'r') as text_file:
    lines = text_file.readlines()


for line in lines:
    driver = webdriver.Chrome()
    driver.maximize_window()
    driver.implicitly_wait(10)
    driver.get('https://seleniumbase.io/demo_page')
    text_box = driver.find_element(By.XPATH, '//textarea[@id="myTextarea"]')
    text_box.send_keys(line)
    sleep(3)  # Pause for 3 seconds just to be able to see the result. It's better to remove this when all the code is ready.
    text_box.submit()  # submit the form if you need it
    driver.quit()

The content of the file myfile.txt is:

1
2
3
  • Related