我用Python3.4编写了这段代码

import urllib.request


def read_text():
    document = open(r"C:\mystuff\udacity\pruebatxt.txt")
    lec = document.read()
    document.close()
    print(lec)
    check_profanity(lec)

def check_profanity (text_to_check):
    print(text_to_check)

最后,我通过改变跟踪线找到了解决方案
    lecture = urllib.request.urlopen("http://www.wdyl.com/profanity?q="+ urllib.parse.quote(text_to_check))
    output=lecture .read()
    print(output)

    lecture.close()
read_text()

它给了我一个错误:
  File "C:\Python34\lib\urllib\request.py", line 1159, in do_request_
    raise URLError('no host given')
urllib.error.URLError: <urlopen error no host given>

怎么了?

最佳答案

urlopen()返回响应,而不是请求。您不能再将其传递给urlopen()
删除多余的urlopen()调用:

lecture = urllib.request.urlopen("http://www.wdyl.com/profanity?q="+text_to_check)
output = lecture.read()

您可能有一个损坏的代理配置;通过检查Python在Windows注册表中找到什么,验证您的代理是明智的:
print(urllib.request.getproxies())

或者完全绕过代理支持:
lecture = urllib.request.urlopen(
    "http://www.wdyl.com/profanity?q="+text_to_check
    proxies={})

关于python - urllib.error.URLError:<urlopen错误未提供主机> python 3,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/24898312/

10-11 17:35