【问题标题】:urllib2 HTTP Error 400: Bad Requesturllib2 HTTP 错误 400:错误请求
【发布时间】:2012-02-09 01:12:33
【问题描述】:

我有一段这样的代码

host = 'http://www.bing.com/search?q=%s&go=&qs=n&sk=&sc=8-13&first=%s' % (query, page)
req = urllib2.Request(host)
req.add_header('User-Agent', User_Agent)
response = urllib2.urlopen(req)

当我输入一个多于一个单词的查询时,例如“the dog”,我收到以下错误。

response = urllib2.urlopen(req)
File "/usr/lib/python2.7/urllib2.py", line 126, in urlopen
return _opener.open(url, data, timeout)
File "/usr/lib/python2.7/urllib2.py", line 400, in open
response = meth(req, response)
File "/usr/lib/python2.7/urllib2.py", line 513, in http_response
'http', request, response, code, msg, hdrs)
File "/usr/lib/python2.7/urllib2.py", line 438, in error
return self._call_chain(*args)
File "/usr/lib/python2.7/urllib2.py", line 372, in _call_chain
result = func(*args)
File "/usr/lib/python2.7/urllib2.py", line 521, in http_error_default
raise HTTPError(req.get_full_url(), code, msg, hdrs, fp)
urllib2.HTTPError: HTTP Error 400: Bad Request

谁能指出我做错了什么? 提前致谢。

【问题讨论】:

  • 在尝试请求带有空格的 URL 时,我还收到了“urllib2.HTTPError: HTTP Error 406: Not Acceptable”。

标签: python urllib2 http-error


【解决方案1】:

你必须使用urllib.quote

【讨论】:

    【解决方案2】:

    您需要在“查询”变量上使用urllib.quote()

    query = urllib.quote(query)
    host = 'http://www.bing.com/search?q=%s&go=&qs=n&sk=&sc=8-13&first=%s' % (query, page)
    

    这会进行必要的 URL 转义,以将 big dog 中的空间转换为 big%20dog

    【讨论】:

      【解决方案3】:

      “狗”返回 400 错误的原因是您没有转义 URL 的字符串。

      如果你这样做:

      import urllib, urllib2
      
      quoted_query = urllib.quote(query)
      host = 'http://www.bing.com/search?q=%s&go=&qs=n&sk=&sc=8-13&first=%s' % (quoted_query, page)
      req = urllib2.Request(host)
      req.add_header('User-Agent', User_Agent)
      response = urllib2.urlopen(req)
      

      它会起作用的。

      但是我强烈建议您使用requests 而不是使用 urllib/urllib2/httplib。这要容易得多,它会为您处理所有这些。

      这是与 python 请求相同的代码:

      import requests
      
      results = requests.get("http://www.bing.com/search", 
                    params={'q': query, 'first': page}, 
                    headers={'User-Agent': user_agent})
      

      【讨论】:

        【解决方案4】:

        我也遇到了同样的问题。原来问题是方法设置不当。当你在 urllib2.urlopen() 中包含 urlencoded 数据时,方法应该设置为 POST,当你排除它时,方法应该是 GET。那么,如何设置方法如下:

        对于 POST 请求

        request_object = urllib2.Request(url)
        method = ("POST", "GET")
        request_object.get_method = lambda: method[0] #If method is set to POST
        url_handle = opener.open(req, data) #If method is set to POST
        

        对于 GET 请求

        request_object = urllib2.Request(url)
        method = ("POST", "GET")
        request_object.get_method = lambda: method[1] #If method is set to GET
        url_handle = opener.open(req) #If method is set to GET
        

        这会将您的 url 请求方法设置为适当的所需方法

        【讨论】:

          【解决方案5】:

          这是一个如何在 Python 3.6 及更高版本中使用 urllib.request 对象的示例。

          import urllib.request
          import json
          from pprint import pprint
          
          url = "some_url"
          
          values = {
              "first_name": "Vlad",
              "last_name": "Bezden",
              "urls": [
                  "https://twitter.com/VladBezden",
                  "https://github.com/vlad-bezden",
              ],
          }
          
          
          headers = {
              "Content-Type": "application/json",
              "Accept": "application/json",
          }
          
          data = json.dumps(values).encode("utf-8")
          pprint(data)
          
          try:
              req = urllib.request.Request(url, data, headers)
              with urllib.request.urlopen(req) as f:
                  res = f.read()
              pprint(res.decode())
          except Exception as e:
              pprint(e)
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2015-06-25
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2014-09-05
            相关资源
            最近更新 更多