我正在尝试在循环中执行循环以在send_keys的消息框中传递变量。当我打开第二个文件“test2.txt”时,我似乎有一个错误,该文件包含我想传递给变量的信息。我对python很新,我不完全确定它意味着什么,并且无法通过搜索来解决它。
非常感谢任何帮助实现这一目标的帮助。
代码段:
with open('test2.txt').read() as lp:
current = 1
for line in lp:
field_box.send_keys("""ID:""", lp)
driver.find_element_by_css_selector('.form-buttons').submit()
time.sleep(2)
完整代码:
import time
from selenium import webdriver
def doAction():
driver = webdriver.Chrome ('/Users/xxx/chromedriver') # Set correct path for chromedriver: https://sites.google.com/a/chromium.org/chromedriver/downloads
driver.get('https://www.site.com.au/login'); # Set which region you're working with
time.sleep(1)
search_box = driver.find_element_by_name('username')
search_box.send_keys('xxx') # Set your e-mail/username
search_box = driver.find_element_by_name('password')
search_box.send_keys('xxx') # Set your password
driver.find_element_by_css_selector('.btn.btn-primary.btn-md.btn-cm.pull-right').click()
time.sleep(2)
with open('test.txt') as fp:
print '============================================'
print 'Starting to disable entities................'
print '============================================'
current = 1
for line in fp:
url = 'https://www.site.com.au/admin/entities/%s' % line
driver.get(url);
time.sleep(3)
driver.find_element_by_css_selector("input[type='radio'][value='false']").click()
field_box_clear = driver.find_element_by_name('disabledReason').clear()
field_box = driver.find_element_by_name('disabledReason')
with open('test2.txt').read() as lp:
current = 1
for line in lp:
field_box.send_keys("""ID:""", lp)
driver.find_element_by_css_selector('.form-buttons').submit()
time.sleep(2)
print "Doing",current,"Of",file_len('test.txt')
current += 1
print '- Disabled entity: %s' % line
print '============================================'
print 'Completed disabling entities................'
print '============================================'
def file_len(fname):
with open(fname) as f:
for i, l in enumerate(f):
pass
return i + 1
if __name__ == "__main__":
doAction()
答案 0 :(得分:1)
问题是你试图用open('test2.txt').read()
statement包裹with
。
为了实现上下文管理器,我们定义了一个包含的类 输入和退出方法。
open('test2.txt').read()
的结果没有实现。而不是,你应该包裹open('test2.txt')
(以自动关闭文件)。
with open('test2.txt') as lp:
current = 1
...