【问题标题】:Python: search XPath using a list of filePython:使用文件列表搜索 XPath
【发布时间】:2021-09-07 22:38:50
【问题描述】:

我正在尝试使用列表或 .txt 文件来搜索跨度中的文本/字符串。 到目前为止,我能够找到一个字符串,但在没有混乱代码的情况下无法合并任何其他字符串。我要找嗨、嗨、你好等

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

文本文件将是:

Hi
Hey
Hello

编辑:在这种情况下,容器会更容易使用吗?

【问题讨论】:

  • 您能否举例说明文本文件的外观?
  • 当然!它将是标准的每个单词。

标签: python selenium xpath


【解决方案1】:

如果我们有这样的列表

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

您可以在 Selenium driver.find_elememt 中解析,如下所示

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

我在这里解析[0],这将是first element,您可以根据需要更改index。

【讨论】:

    【解决方案2】:

    这是我想出的:

    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()
    

    我使用 Wikipedia 主页来测试我的脚本,并将一些链接名称放入一个文本文件中。文本文件中的前三个出现在主页上,第四个没有。

    这是运行此设置时应该得到的输出:

    found
    found
    found
    Could not find Random articles
    

    这里的关键是使用 word.strip() 将文本文件中的单词与页面上的元素进行匹配。

    请注意:我使用的是 a 标签而不是 span 标签。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-01
      • 2023-03-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-28
      • 2013-03-06
      相关资源
      最近更新 更多