使用 urllib 时出现 400 Bad Request HTTPError 异常

400 Bad Request HTTPError exception when using urllib

我想阅读使用 python3 请求的 url 的 output/contents。当只传递一个字符串作为参数时它工作完美,但当将整个句子作为参数传递时它不起作用。

为了简单起见,我尝试在下面给定的代码中用两个不同的部分来表达这两种情况。

什么是错误?以及如何解决?

但是,当我直接在网络浏览器选项卡中打开时,第二个 link 运行良好。

### code """
 import urllib.request
 def check_curse1():
 content = "hello"  ##### line of attention
    link="http://www.wdylike.appspo
            t.com/?q="+content
    #print(link)
    connection = urllib.request.urlopen(link)
    #print(connection)
    output = connection.read()
    print(output)
    connection.close()
  def check_curse2():
    content = "hi. Need help"  
  #####line of attention
    link="http://www.wdylike.appspo
            t.com/?q="+content
    #print(link)
    connection = urllib.request.urlopen(link)
    #print(connection)
    output = connection.read()
    print(output)
    connection.close()
  print("case 1 working")
  check_curse1()
  print("\n")
  print("case 2 not working")
  check_curse2()

## output part ##
case 1
b'false'
case 2
Traceback (most recent call last):
 File "error.py", line 26, in <module>
  check_curse2()
 File "error.py", line 16, in check_curse2
  connection = urllib.request.urlopen(link)
 File "/usr/lib/python3.6/urllib/request.py", line 223, in urlopen
  return opener.open(url, data, timeout)
 File "/usr/lib/python3.6/urllib/request.py", line 532, in open
  response = meth(req, response)
 File "/usr/lib/python3.6/urllib/request.py", line 642, in 
   http_response
   'http', request, response, code, msg, hdrs)
File "/usr/lib/python3.6/urllib/request.py", line 570, in error
  return self._call_chain(*args)
File "/usr/lib/python3.6/urllib/request.py", line 504, in 
  _call_chain
  result = func(*args)
File "/usr/lib/python3.6/urllib/request.py", line 650, in 
  http_error_default
  raise HTTPError(req.full_url, code, msg, hdrs, fp)
urllib.error.HTTPError: HTTP Error 400: Bad Request

在触发请求之前,您需要使用空格或特殊字符对字符串进行编码。

import urllib.request
def check_curse1():
    content = "hello"  ##### line of attention
    link="http://www.wdylike.appspot.com/?q="+content
    #print(link)
    connection = urllib.request.urlopen(link)
    #print(connection)
    output = connection.read()
    print(output)
    connection.close()
def check_curse2():
    content = {'q': "hi. Need help"}  #####line of attention
    encoded_content = urllib.parse.urlencode(content)
    link="http://www.wdylike.appspot.com/?"+encoded_content
    #print(link)
    connection = urllib.request.urlopen(link)
    #print(connection)
    output = connection.read()
    print(output)
    connection.close()

print("case 1 working")
check_curse1()
print("\n")
print("case 2 not working")
check_curse2()

输出:

case 1 working
b'false'


case 2 not working
b'false'