首页 > 解决方案 > 有什么问题吗?

问题描述

我正在学习 python Selenium,并创建了一个“电子邮件”列表:“密码”。我需要在正确的位置插入这些电子邮件,然后是密码,然后是登录按钮。这是代码:

f = open('users.txt','r')
for line in f.readlines():
    print(line)
    mail = line[0:line.index(':')]
    line = line[line.index(':')+1:]
    password = line
    email_input = driver.find_element_by_xpath('//*[@id="email"]')
    email_input.click()
    email_input.send_keys(mail)
    password_input = driver.find_element_by_xpath('//*[@id="password"]')
    password_input.click()
    password_input.send_keys(password)
    lgn_btn = driver.find_element_by_css_selector('#sign-in')
    lgn_btn.click()
    n_url = driver.current_url
    time.sleep(5)
    driver.refresh() 

我得到的错误是:

mail = line[0:line.index(':')]
ValueError: substring not found

txt文件是:

g_santeusanio@arcor.de:sportpark13 
mrtslabbert@absamail.co.za:oohethooq12313w 
lauriecd@absamail.co.za:christcorem

标签: pythonseleniumselenium-webdriver

解决方案


你应该使用

line.find(':')

而不是line.index(':') 这是因为 index() 方法在 中搜索子字符串并返回它的索引。

既然要在字符串中查找单个字符,就应该使用find()方法!

用于两个代码的文本文件,演示:

在此处输入图像描述

根据@John Gordon 的评论进行编辑

当字符串中不存在此类值时,该index()方法返回值错误。使用的文本文件有 2 个空行。该find()方法返回 - 1而不是错误。

请注意,为问题中使用的代码块打印了第一对邮件和密码

在此处输入图像描述

当它在第二行(为空)中搜索值时,它会引发ValueError. 另一方面,如果您在使用该find()方法时看到输出(下面附加的img),它只会打印出空字符串并继续前进!

因此,find()当您不确定要搜索的值是否在字符串中时,最好使用它。

根据@Chris 的评论进行编辑

这是我使用的代码:

for line in f.readlines():
    # print(line)
    mail = line[0:line.find(':')]
    password = line[line.find(':') + 1:]
    print(mail)
    print(password)

我收到的您粘贴的文本的输出是这样的:

在此处输入图像描述


推荐阅读