python - 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
解决方案
我假设您收到一个看起来像这样的错误:
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)
推荐阅读
- python - 更改绑定类中的变量会重复布局并导致 kivy 崩溃
- javascript - 如何拆分缓冲字符串以以特定字节大小作为多个数据包发送?
- ruby-on-rails - 搜索表单找不到具有 'id'= 的用户
- node.js - AWS Elastic Beanstalk 上的 node/express/react 项目无法获取/错误
- html - 如果标签为空,则在取消选择时为所需的输入标签设置样式
- list - 检查动态谓词是否包含值的方法
- bash - bash 脚本无法处理 Windows 的 linux 子系统上的空格和破折号
- list - 球拍“第一个:需要一个非空列表;给定:空”
- go - 如何将任意 proto 消息作为输入并用它调用 protojson.Marshal
- javascript - 为什么我的 JavaScript 对象函数将其参数名称分配为键而不是参数名称?