首页 > 解决方案 > Python,返回 url 列表的 IP 地址

问题描述

我正在尝试使用 Python 自动执行一项任务,其中有一个 .txt 文件的 url 列表并将其转换为 IP 地址的 .txt 文件列表。Domain.txt 每一行都有一个活动的 url,IP.py 如下:

import socket

urls = open('domain.txt', 'r')

for lines in urls:
    IP = socket.gethostbyname(lines)
print(IP)

我通过调用它来错误地运行这个脚本:

$ python3 IP.py domain.txt

这个脚本的正确语法是什么?

我得到的输出错误是:

Traceback (most recent call last):
  File "IP.py", line 6, in <module>
    IP = socket.gethostbyname(lines)
socket.gaierror: [Errno -5] No address associated with hostname

标签: python

解决方案


我假设您收到一个看起来像这样的错误:

Traceback (most recent call last):
  File "StackOverflow.py", line 7, in <module>
    IP = socket.gethostbyname(lines)
socket.gaierror: [Errno 11001] getaddrinfo failed

在您的情况下,问题不在于套接字库,而可能是您输入输入的方式。例如,尝试运行这段代码,看看会发生什么:

urls = open('lowes.txt', 'r')

links = []
for link in urls.readlines():
    links.append(link)

print(links)

这是一个示例输出:

['google.com\n', 'yahoo.com\n', 'facebook.com']

看到\n最后了吗?每当您将其放入套接字库时,它就会崩溃,因为没有名为"google.com\n".

不过,这很容易解决,只需确保使用line.strip(). 像这样:

import socket

urls = open('lowes.txt', 'r')

for lines in urls:
    IP = socket.gethostbyname(lines.strip())
    print(IP)

推荐阅读