如何从列表中选择一个文本,用所选的文本执行特定任务,然后在Selenium Python中选择下一行文本



我有一个txt文件,我希望selenium遍历该txt文件。它应该选择第一行,执行某些操作,然后选择第二行,也执行某些操作。它应该一直这样做,直到到达第10行,然后休息5分钟。选择接下来的10条,休息5分钟,直到所有线路都工作完毕。

但我被困在了第一行,它只选择了txt文件的最后一行。这是我的密码;

# Picks the first Keyword
file = open ('Keywords.txt', "r")
lines = file.readlines()
for line in lines:
Keywordspace = driver.find_element_by_id('keyword')
Keywordspace.send_keys(line.strip())
# Togls on Title ( action to be performed)
checkBoxtitle = driver.find_element_by_xpath("//*[@id='create_article_form']/div[1]/div/div[4]/div[2]/div[2]/div/div/label")
# Scroll to checkbox if its not in screen
driver.execute_script("arguments[0].scrollIntoView();", checkBoxtitle)
driver.execute_script("arguments[0].click();", checkBoxtitle)

#Create With The First Line ( second action to be performed)
create=driver.find_element_by_id('create_button')
create.click()
# Clear First Line
driver.find_element_by_id('keyword').clear()
#Adds Second Keyword
for line in lines:
Keywordspace = driver.find_element_by_id('keyword')
Keywordspace.send_keys(line.strip())

这就是我所指的。这样,for循环下的所有代码将在每次迭代中执行。这不是你想要的吗。。。

file = open ('Keywords.txt', "r")
lines = file.readlines()
for line in lines:
Keywordspace = driver.find_element_by_id('keyword')
Keywordspace.send_keys(line.strip())
# Togls on Title ( action to be performed)
checkBoxtitle = driver.find_element_by_xpath(
"//*[@id='create_article_form']/div[1]/div/div[4]/div[2]/div[2]/div/div/label")
# Scroll to checkbox if its not in screen
driver.execute_script("arguments[0].scrollIntoView();", checkBoxtitle)
driver.execute_script("arguments[0].click();", checkBoxtitle)
# Create With The First Line ( second action to be performed)
create = driver.find_element_by_id('create_button')
create.click()
# Clear First Line
driver.find_element_by_id('keyword').clear()

检查迭代的小测试代码:

file = open('keywords.txt', 'r')
lines = file.readlines()
for line in lines:
print(line)
print(f'action_1: {line}')
print(f'action_2: {line}')
print(f'action_3: {line}')
file.close()

输出:

keyword_1
action_1: keyword_1
action_2: keyword_1
action_3: keyword_1
keyword_2
action_1: keyword_2
action_2: keyword_2
action_3: keyword_2
keyword_3
action_1: keyword_3
action_2: keyword_3
action_3: keyword_3

最新更新