python - 有什么问题吗?
问题描述
我正在学习 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
解决方案
你应该使用
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)
我收到的您粘贴的文本的输出是这样的:
推荐阅读
- javascript - 如何将 EJS 变量传递给 LightGallery 的 data-src
- c++ - 释放动态内存时出现 C++ 错误
- python - 即使使用 DJANGO 模型表单提交后,图片也没有在数据库中更新
- python - 如何在不影响滚动条颜色的情况下更改 QScrollArea 的背景颜色?
- javascript - 用于写博客的 Django 表单
- javascript - Webpack 在尝试构建 JSX 时抛出错误
- mysql - 如何更新具有键值对的 SQL 列?
- html - 日期选择器与引导程序对齐的问题
- caching - 寻求作曲家包的开源存储库,通过它代理我的构建请求,并构建本地缓存以供将来使用
- javascript - 反应组件中的多个输入,保存每个索引