首页 > 解决方案 > http.client.InvalidURL:非数字端口:'//water-lined.net' 错误?

问题描述

我一直在尝试制作一个脚本来检查一个随机网站是否存在,如果它确实存在则打开它,但我不断收到一堆不同的错误。这是我的代码:

import webbrowser
import time
import random
import http.client
from random_word import RandomWords
r=RandomWords()
while True:
    possible_things = random.choice([".com",".net"])
    WEB = "http://"+r.get_random_word()+possible_things
    c = http.client.HTTPConnection(WEB)
    if c.getresponse().status == 200:
        seconds = random.randint(5,20)
        print("Web site exists; Website: "+WEB+" ; Seconds: "+seconds)
        time.sleep(seconds)
        webbrowser.open(WEB)
        print("Finished countdown, re-looping...")
    else:
        print('Web site DOES NOT exists; Website: '+WEB+'; re-looping...')

这是错误:

Traceback (most recent call last):
  File "C:\Users\[REDACTED]\AppData\Local\Programs\Python\Python37-32\lib\http\client.py", line 877, in _get_hostport
    port = int(host[i+1:])
ValueError: invalid literal for int() with base 10: '//water-lined.net'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "Troll.py", line 10, in <module>
    c = http.client.HTTPConnection(WEB)
  File "C:\Users\[REDACTED]\AppData\Local\Programs\Python\Python37-32\lib\http\client.py", line 841, in __init__
    (self.host, self.port) = self._get_hostport(host, port)
  File "C:\Users\[REDACTED]\AppData\Local\Programs\Python\Python37-32\lib\http\client.py", line 882, in _get_hostport
    raise InvalidURL("nonnumeric port: '%s'" % host[i+1:])
http.client.InvalidURL: nonnumeric port: '//water-lined.net'

标签: pythonpython-3.xhttp.client

解决方案


WEB = "http://"+r.get_random_word()+possible_things
c = http.client.HTTPConnection(WEB)

在这些行的第一行中,您创建一个 URL,以 http:// 开头。在第二行中,您将它传递给一个不需要 URL 的函数,而是一个带有可选:和端口号的主机名。由于您的字符串在“http”之后包含一个冒号,因此“http”将被假定为主机名,冒号后面的所有内容,即“//something.tld”被解释为端口号 - 但它不能转换为整数,因此错误。

您可能想要做的是以下几方面的事情:

host = r.get_random_word() + possible_things
WEB = 'http://' + host
c = http.client.HTTPConnection(host)
c.request('GET', '/')
resp = c.getresponse()
if resp.status == 200:

等等


推荐阅读