用 Python 个请求迭代 URL 个

Iterate URL's with Python Requests

我正在尝试遍历从 CSV 中提取的 URI 列表。我会认为 requests 不能在 URL 字符串中使用变量,但我想检查一下是否有人对如何实现这样的工作有任何想法。

with open(fwinfo) as csvfile:
    reader = csv.DictReader(csvfile)
    for row in reader:
        try:
            rkey = requests.get('https://'row['ip_address'])
            if rkey.status_code == 200:

您得到的是 SyntaxError,这意味着您的 Python 语法有误;这不是 requests 图书馆的错。

您需要在此处使用字符串连接或字符串格式化;您不能只在字符串后放置一个变量。

+ 连接字符串:

rkey = requests.get('https://' + row['ip_address'])

或者您可以使用 str.format() 将 CSV 值插入到字符串中:

rkey = requests.get('https://{}'.format(row['ip_address']))

考虑到 HTTP 服务器通常为来自给定 IP 地址的多个网站提供服务;根据 Host header 提供不同的站点。考虑到仅使用 IP 地址时,您可能需要手动添加主机。

我想你想要的是:

rkey = requests.get('https://{}'.format(row['ip_address']))