【问题标题】:How do I enter a list of text from a txt file to a variable in python?如何将txt文件中的文本列表输入到python中的变量?
【发布时间】:2021-07-15 01:21:07
【问题描述】:
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")

我想将 List.txt 中的代码列表输入到 code,只要 activation 为真,并根据列表中的元素数量创建一个循环

例如,如果列表有 5 个代码,我想看看 activation 是否为真。如果是真的会超时120秒(这部分我可以做) 然后120秒后,会输入list.txtcode的代码

我仍在学习 python,我正在尝试不同的东西并在 python 中学习新单词

【问题讨论】:

  • 任何体面的教程都应该涵盖这一点;其中大部分是免费的,所以没有理由不经历一两个。回到基础。 SO 并不打算取代那些。
  • @JustinEzequiel 我搜索了他们,但没有找到我想要的。我可能没有使用正确的术语。这叫什么?
  • 不清楚是要将值赋给代码变量,还是将文件内容粘贴到输入框中。如果是后者,请使用element.send_keys(text)
  • 如果您在分隔行中有代码codes = open(...).read().split('\n')。稍后您必须使用for-loop 到send_key 与单个代码到input 并再次获得`activation

标签: python python-3.x selenium selenium-webdriver


【解决方案1】:

我不知道我是否理解你的问题,但如果你有分隔行中的代码,那么你可以这样做

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

最好在路径中使用 \\,因为 \ 用于特殊字符,例如 \n(新行)、\t(制表符)等 - 即使在路径中 - 单个 \ 也会产生问题。或者为raw string 使用前缀r

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

接下来您需要for-loop 来获取单个代码,将其发送到输入并检查结果。

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

您可能需要在每个循环中再次使用find_element,因为find_element 引用了内存中的对象,当您放入code 时,它可能会更改HTML,并且元素可以移动到内存中的不同位置。

您也可以尝试使用//classesids 找到更短的xpath

【讨论】:

  • 是的,感谢您的帮助,它成功了!我主要是因为\n而面临问题。
  • @TasrifRahman 那么你为什么不接受这个答案呢?
  • @Prophet 抱歉,我是这个社区的新手,所以我忘记了。我“回答”了它
猜你喜欢
  • 1970-01-01
  • 2018-01-05
  • 1970-01-01
  • 1970-01-01
  • 2017-07-13
  • 1970-01-01
  • 1970-01-01
  • 2015-02-27
  • 2022-12-18
相关资源
最近更新 更多