25

私はこのようなコードを持っています

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」のような 2 つ以上の単語を入力すると、次のエラーが表示されます。

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

誰かが私が間違っていることを指摘できますか? 前もって感謝します。

4

5 に答える 5

63

「the dog」が 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)

それが動作します。

ただし、urllib/urllib2/httplib を使用する代わりにリクエストを使用することを強くお勧めします。はるかに簡単で、これらすべてを処理します。

これは、Python リクエストと同じコードです。

import requests

results = requests.get("http://www.bing.com/search", 
              params={'q': query, 'first': page}, 
              headers={'User-Agent': user_agent})
于 2012-01-12T18:38:37.077 に答える
6

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 dogbig%20dogます。

于 2012-01-12T18:36:37.110 に答える
4

urllib.quoteを使用する必要があります

于 2012-01-12T18:35:15.453 に答える
2

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)
于 2019-08-08T14:21:44.360 に答える
0

私も同じ問題に遭遇しました。問題は、メソッドが不適切に設定されていたことです。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 リクエスト メソッドが適切な必須メソッドに設定されます

于 2015-08-22T05:54:22.177 に答える