gpt4 book ai didi

python - socket.gaierror : [Errno 11001] getaddrinfo failed"in python, 使用简单的自定义 Web 浏览器

转载 作者:行者123 更新时间:2023-12-03 12:07:17 24 4
gpt4 key购买 nike

这是我正在构建的网络浏览器的语法:

"import socket
mysock=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
print('Please Enter the website url and port below, else the default port will be used')
print('\rWebsite:')
website=input()
print('\rPORT:')
port=input()
if len(website)<2:
print("/n You have entered an Invalid Link")
if len(port)<1:
port=80
while len(website)>1:
mysock.connect((website, (int(port))))
cmd=('GET'+website+'HTTP/1.0 \r\n\r\n').encode()
mysock.send(cmd)
while True:
data=mysock.recv(512)
if len(data) < 1:
break
print(data.decode(),end='')
mysock.close()
"
我正在尝试访问此链接:
http://data.pr4e.org/romeo.txt通过端口 80 但接收
"Traceback (most recent call last):
File "C:\Users\PLAY\Documents\python work\browser.py", line 13, in <module>
mysock.connect((website, (int(port))))
socket.gaierror: [Errno 11001] getaddrinfo failed"
这里发生了什么,我该如何改进它?我只是在乱搞代码,想了解更多,让它更实用,这样我就可以在它之上构建。
提前致谢。

最佳答案

您不能将整个 URL 传递给 socket.connect() ,只有一个 IP/主机名和一个端口号。因此,您需要解析用户的输入并将其分解为其组成组件,然后您可以对它们采取行动。
如果用户输入 http://data.pr4e.org/romeo.txt ,您需要将其分解为 http , data.pr4e.org , 和 /romeo.txt .将套接字连接到 data.pr4e.org在端口 80 上(因为使用了 http),然后发送对 GET /romeo.txt HTTP/1.0\r\n\r\n 的请求(注意空格!)。
Python 有一个 urllib.parse 用于解析 URL 的模块。
更好的选择是使用 urllib.request 模块,甚至是 Requests库,而不是手动的套接字。让模块/库为您完成所有 URL 解析和套接字处理。你给他们一个 URL 来访问,他们会给你从那个位置下载的数据。

关于python - socket.gaierror : [Errno 11001] getaddrinfo failed"in python, 使用简单的自定义 Web 浏览器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65572244/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com