如何使用 urllib 为 get 方法传递参数?

How to pass arguments for get method with urllib?

选择title输入wordpress.

响应网页如下

这是我的 python 代码,用于为 python3 的 get 方法传递参数。

import urllib.request
import urllib.parse
url = 'http://www.it-ebooks.info/'
values = {'q': 'wordpress','type': 'title'}
data = urllib.parse.urlencode(values).encode(encoding='utf-8',errors='ignore')
headers = { 'User-Agent' : 'Mozilla/5.0 (Windows NT 10.0; WOW64; rv:50.0) Gecko/20100101 Firefox/50.0' }
request = urllib.request.Request(url=url, data=data,headers=headers,method='GET')
response = urllib.request.urlopen(request)
buff = response.read()
html = buff.decode("utf8")
print(html)

我无法得到想要的输出网页。 如何在我的示例中使用 urllib 为 get 方法传递参数?

urllib.request.Requestdata kwarg 仅用于 POST 请求,因为它修改了请求的主体。

GET 请求仅使用 URL 参数,因此您应该将这些附加到 url:

params = '?q=wordpress&type=title'
url = 'http://www.it-ebooks.info/search/{}'.format(params)

您当然可以花时间将其概括为通用函数。

如果使用名为 requests

的库会更好

import requests


headers = {
    'DNT': '1',
    'Accept-Encoding': 'gzip, deflate, sdch',
    'Accept-Language': 'es-ES,es;q=0.8,en;q=0.6',
    'Upgrade-Insecure-Requests': '1',
    'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36',
    'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
    'Referer': 'http://www.it-ebooks.info/',
    'Connection': 'keep-alive',
}

r = requests.get('http://www.it-ebooks.info/search/?q=wordpress&type=title', headers=headers)

print r.content