我试图在一个循环中做一个循环,以在 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()
请您参考如下方法:
问题是你试图用 with
statement 包装 open('test2.txt').read()
.
To implement a context manager, we define a class containing an enter and exit method.
open('test2.txt').read()
的结果没有实现。相反,您应该包装 open('test2.txt')
(以自动关闭文件)。
with open('test2.txt') as lp:
current = 1
...