Python: search XPath using a list of file

Viewed 131

I am trying to use a list or a .txt file to search for text/string in a span. So far I am able to find one string but not incorporate any others without messy code. I want to look for Hi, Hey, Hello, etc

browser.find_element_by_xpath('//span[text()= "Hey"]')

The text file will be:

Hi
Hey
Hello

Edit: Would a contain be easier to use in this case?

2 Answers

Here is what I have come up with:

dummy.txt

Main Page
Contents
Current events
Random articles

test.py

from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as ec
from selenium.webdriver.support.wait import WebDriverWait
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options

options = Options()
options.add_argument('--no-sandbox')
options.add_argument('--start-maximized')
options.add_argument('--disable-extensions')
options.add_argument('--disable-dev-shm-usage')
options.add_argument('--ignore-certificate-errors')
options.add_argument('--enable-logging')
service = Service(ChromeDriverManager().install())
driver = webdriver.Chrome(service=service, options=options)
url = "https://en.wikipedia.org/wiki/Main_Page"
driver.get(url)
WebDriverWait(driver, 30).until(ec.presence_of_element_located((By.XPATH, "/html/body/div[5]/div[2]/nav[1]/div/ul/li[1]/a")))
try:
    with open("./dummy.txt") as in_file:
        for word in in_file.readlines():
            if word.strip() in driver.find_element(By.XPATH, f'//a[text()= "{word.strip()}"]').text:
                print("found")
except NoSuchElementException as e:
    print(f"Could not find {word}")
driver.quit()

I used the Wikipedia homepage to test out my script, and put a few link names into a text file. The first three in the text file are present on the homepage and the fourth one is not.

Here is the output you should get if you run this setup:

found
found
found
Could not find Random articles

The key here is to use word.strip() to match the words in the text file to an element on the page.

PLEASE NOTE: I used an a tag instead of span tag.

If we have a list like this

text_list = ['Hi', 'Hey', 'Hello']

You can parse in the Selenium driver.find_elememt like below

browser.find_element_by_xpath(f'//span[text()= "{text_list[0]}"]')

Here I am parsing [0] which will be the first element, you can change the index as you wish to.

Related