Python:阅读URL列表,同时传入参数

7fhtutme  于 4个月前  发布在  Python
关注(0)|答案(2)|浏览(67)

Python的问题在这里.我有两个文件,其中包含以下数据:
hosts.txt

google.com
target.com
bing.com

字符串
strings1.txt

x
y
z


我尝试通过阅读hosts.txt中的主机列表,同时传入strings1.txt中的字符串列表作为查询参数来构造URL并向其发出GET请求。然而,My Script只向hosts.txt的第1行和strings1.txt中的所有字符串发出请求,但随后脚本终止(参见:输出)。我如何将查询参数列表传递给第一个主机,然后使用相同的查询参数在hosts.txt文件的第2行移动到下一个主机等等?我尝试使用next()方法,但遇到了麻烦。任何帮助都非常感谢。谢谢。

我的剧本

with open('hosts.txt','r') as file:
        with open('strings1.txt','r') as strings:
            for line in file:
                host = line.strip()
                for string in strings:
                    url = f"https://{host}/?test={string}"
                    resp = requests.get((url)).status_code
                    print(f'Results for {url}\n{test}')

输出

Results for https://google.com/?test=x
 302
Results for https://google.com/?test=y
 302
Results for https://google.com/?test=z
 302
[...SCRIPT TERMINATES...]

uqzxnwby

uqzxnwby1#

string迭代器已经耗尽了(它迭代了strings1.txt文件中的行,所以你只能看到一次对主机的迭代)。相反,将主机/字符串读取到一个列表中,然后发出请求:

with open("hosts.txt", "r") as f_hosts:
    hosts = list(map(str.strip, f_hosts))

with open("strings.txt", "r") as f_strings:
    strings = list(map(str.strip, f_strings))

for h in hosts:
    for s in strings:
        url = f"https://{h}/?test={s}"
        print(url)
        # requests.get(url)
        # ...

字符串
印刷品:

https://google.com/?test=x
https://google.com/?test=y
https://google.com/?test=z
https://target.com/?test=x
https://target.com/?test=y
https://target.com/?test=z
https://bing.com/?test=x
https://bing.com/?test=y
https://bing.com/?test=z

hl0ma9xz

hl0ma9xz2#

看起来问题与您如何在循环内从strings1.txt中阅读字符串有关。一旦到达文件的末尾,后续读取尝试将不会产生任何更多值。要为每个主机重新遍历strings1.txt的行,您需要重新打开文件或返回到开头。

import requests

with open('hosts.txt', 'r') as file:
    with open('strings1.txt', 'r') as strings:
        for line in file:
            host = line.strip()
            
            # Rewind the strings file to the beginning for each host
            strings.seek(0)
            
            for string in strings:
                string = string.strip()
                url = f"https://{host}/?test={string}"
                resp = requests.get(url).status_code
                print(f'Results for {url}\n{resp}')

字符串

相关问题