urllib.error.URLError:<urlopen error =“”no =“”host =“”given =“”> python 3 </urlopen>

时间:2014-07-22 21:38:18

标签: python python-3.x urllib urlopen

我在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>

可能出现什么问题?

2 个答案:

答案 0 :(得分:3)

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

答案 1 :(得分:1)

您的代码返回二进制字符串。将它解码为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)