使用urllib时出现400错误的请求HTTPError异常

时间:2019-04-17 12:00:35

标签: python python-3.x urllib

我想读取使用python3请求的url的输出/内容。当仅传递一个字符串作为参数时,它是完美的,但是当传递整个句子作为参数时,效果不佳。

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

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

但是,当我直接在Web浏览器选项卡中打开时,第二个链接可以正常工作。

### code """
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 = "hi. Need help"  #####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()
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

1 个答案:

答案 0 :(得分:0)

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

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'