从 .txt 文件发送 post 请求

时间:2021-02-12 13:44:34

标签: python python-3.x python-requests

我是 Python 新手,正在寻求帮助 :)

我创建了一个简单的脚本来检查 IPVoid 中的 IP 信誉(来自list.txt):

import requests
import re

URL = "https://www.ipvoid.com/ip-blacklist-check/"
ip = open('lists.txt')
DATA = {"ip":ip}

r = requests.post(url = URL, data = {"ip":ip})
text = r.text
bad_ones= re.findall(r'<i class="fa fa-minus-circle text-danger" aria-hidden="true"></i> (.+?)</td>', text)

print(bad_ones)

lists.txt 包含 IP 列表:

  • 8.8.8.8
  • 4.4.4.4

等等。

但是,该脚本只占用了 1 行脚本 - 我想做“批量”检查。

请指教:)

2 个答案:

答案 0 :(得分:0)

不清楚txt文件中的ip地址是否是一行一行的组织,但我假设是这样。

您可以执行以下操作

import requests
import re

URL = "https://www.ipvoid.com/ip-blacklist-check/"

bad_ones = []
with open('lists.txt') as f:
    for ip in f.readlines():
        r = requests.post(url = URL, data = {"ip":ip.strip()})
        text = r.text
        bad_ones.append(re.findall(r'<i class="fa fa-minus-circle text-danger" aria-hidden="true"></i> (.+?)</td>', text))

print(bad_ones)

with open('lists.txt') as f 语句让您 打开文件并将生成的 io 对象命名为 f,当到达 'with' 块的末尾时,该文件将被关闭,而不会显式调用 f.close()

现在对于批处理模式,它是对文本文件每一行的简单循环,通过在每个 strip() 字符串(行文本文件)。

答案 1 :(得分:0)

我什至不确定你上面的程序是否有效。你程序中的 ip 变量基本上是一个 io 对象。

您需要的是一个 for 循环来为每个 IP 发送请求。

如果 API 接受它们,您可以进行批量检查

import requests
import re

URL = "https://www.ipvoid.com/ip-blacklist-check/"
ips = open('lists.txt')

for ip in ips.readlines(): 
    DATA = {"ip":ip}

    r = requests.post(url = URL, data = {"ip":ip})
    text = r.text
    '''Your processing goes here..'''

还探索使用 with 子句打开和关闭文件。