English 中文(简体)
urllib2 HTTP Error 400: Bad Request
原标题:urllib2 HTTP Error 400: Bad Request

我有这样一部法典。

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)

并且当我提出疑问时,像“狗”这样一字就会产生以下错误。

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

Can anyone point out what im doing wrong? Thanks in advance.

最佳回答

The reason that "the dog" returns a 400 Error is because you aren t escaping the string for a 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)

它将开展工作。

然而,我高度建议你使用,而不是使用urllib/urllib2/httplib。 这对你来说,这非常容易,而且会给你带来所有这一切。

This is the same code with python requests:

import requests

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

您需要使用<代码>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 escaping将空间转换为big dogbig%20dog

页: 1

这方面的一个例子是如何使用血缘。 请求在A/63/13和3。

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)

我也遇到了同样的问题。 问题在于确定的方法是不适当的。 如果你在urllib2.urlopen()中包含长条码数据,那么该方法应当被定为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

这将使你的要求方法符合适当的必要方法。





相关问题
Can Django models use MySQL functions?

Is there a way to force Django models to pass a field to a MySQL function every time the model data is read or loaded? To clarify what I mean in SQL, I want the Django model to produce something like ...

An enterprise scheduler for python (like quartz)

I am looking for an enterprise tasks scheduler for python, like quartz is for Java. Requirements: Persistent: if the process restarts or the machine restarts, then all the jobs must stay there and ...

How to remove unique, then duplicate dictionaries in a list?

Given the following list that contains some duplicate and some unique dictionaries, what is the best method to remove unique dictionaries first, then reduce the duplicate dictionaries to single ...

What is suggested seed value to use with random.seed()?

Simple enough question: I m using python random module to generate random integers. I want to know what is the suggested value to use with the random.seed() function? Currently I am letting this ...

How can I make the PyDev editor selectively ignore errors?

I m using PyDev under Eclipse to write some Jython code. I ve got numerous instances where I need to do something like this: import com.work.project.component.client.Interface.ISubInterface as ...

How do I profile `paster serve` s startup time?

Python s paster serve app.ini is taking longer than I would like to be ready for the first request. I know how to profile requests with middleware, but how do I profile the initialization time? I ...

Pragmatically adding give-aways/freebies to an online store

Our business currently has an online store and recently we ve been offering free specials to our customers. Right now, we simply display the special and give the buyer a notice stating we will add the ...

Converting Dictionary to List? [duplicate]

I m trying to convert a Python dictionary into a Python list, in order to perform some calculations. #My dictionary dict = {} dict[ Capital ]="London" dict[ Food ]="Fish&Chips" dict[ 2012 ]="...

热门标签