【问题标题】:urllib.error.URLError: <urlopen error no host given> python 3urllib.error.URLError: <urlopen error no host given> python 3
【发布时间】:2014-07-22 21:38:18
【问题描述】:

我在 python 3.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>

可能出了什么问题?

【问题讨论】:

  • 感谢指正

标签: python python-3.x urllib urlopen


【解决方案1】:

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={})

【讨论】:

  • print(urllib.request.getproxies()) 显示什么?将proxies={} 添加到urlopen() 调用中是否有效?
  • 感谢您的帮助,在代码中我更改了一行,我找到了解决方案
【解决方案2】:

您的代码返回一个二进制字符串。最好解码成ascii格式:

with urllib.request.urlopen("http://www.wdyl.com/profanity?q=" + urllib.parse.quote(text_to_check)) as response:
    output = response.read()
output = output.decode('ascii')
print (output)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-12-04
    • 2021-12-06
    • 2018-09-18
    • 1970-01-01
    • 2015-01-22
    • 2019-07-22
    • 2018-03-24
    相关资源
    最近更新 更多