Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python输出整个文本文件,而不是逐行输出_Python_Python 3.x_Selenium_Python 3.6 - Fatal编程技术网

Python输出整个文本文件,而不是逐行输出

Python输出整个文本文件,而不是逐行输出,python,python-3.x,selenium,python-3.6,Python,Python 3.x,Selenium,Python 3.6,我试图将文本文件中的数据逐行输出到网站上的搜索框中。我正在使用Selenium与网页交互 但是,当我的代码写入网页上的文本字段时,它会粘贴文本文件的全部内容,而不是第一行,加载页面,然后搜索第二行,依此类推第四行。。。。。请参见下面我的代码: with open("SerialNumbers.txt") as sn: for line in sn: search_field = driver.find_element_by_id('criteria[1][1]')

我试图将文本文件中的数据逐行输出到网站上的搜索框中。我正在使用Selenium与网页交互

但是,当我的代码写入网页上的文本字段时,它会粘贴文本文件的全部内容,而不是第一行,加载页面,然后搜索第二行,依此类推第四行。。。。。请参见下面我的代码:

with open("SerialNumbers.txt") as sn:
    for line in sn:
        search_field = driver.find_element_by_id('criteria[1][1]')
        search_field.click()
        serials = sn.read().splitlines()
        search_field.send_keys(serials)
        search_field.send_keys(Keys.ENTER)
将我的文本文件序列的第一行发送到搜索_字段时,它开始写入SerialNumbers.txt的全部内容


如果可能,请告知我哪里出错,因为我确信将变量定义为sn.read.splitlines应该告诉python从列表中逐行读取

with open(r'c:\Users\xf01145\Downloads\scores.txt') as file:
    lines = file.readlines()
    for line in lines:
        print(line, end='')
查看您的代码,您已经在遍历文件的行,因为序列号中的for行:。但是,serials=sn.read.splitlines会导致serials包含文件中的行列表。由于send_keys可以获取要发送的密钥列表,因此它只发送文件中的所有数据。如果您想搜索一行,然后搜索下一行,等等,那么我建议您只需在第一个send_键中输入一行,如下所示:

您可能需要修剪行尾,因为每行都可能包含\n字符。您可以使用str.rstrip执行此操作,如果这不会中断您的搜索,它将删除所有尾随的空白字符

或者,您可以执行sn.read.splitlines并迭代如下操作:

with open("SerialNumbers.txt") as sn:
    for line in sn:
        search_field = driver.find_element_by_id('criteria[1][1]')
        search_field.click()
        search_field.send_keys(line)
        search_field.send_keys(Keys.ENTER)
with open("SerialNumbers.txt") as sn:
    serials = sn.read().splitlines()
    for serial in serials:
        search_field = driver.find_element_by_id('criteria[1][1]')
        search_field.click()
        search_field.send_keys(serial)
        search_field.send_keys(Keys.ENTER)