Python 3:HTTP错误405:不允许的方法

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python 3:HTTP错误405:不允许的方法相关的知识,希望对你有一定的参考价值。

我收到'HTTP错误405:方法不允许'错误。我的代码是

import urllib.request
import urllib.parse

try:
    url = 'https://www.google.com/search'
    values = {'q': 'python programming tutorials'}

    data = urllib.parse.urlencode(values)
    data = data.encode('utf-8')  # data should be bytes
    headers = {}
    headers['User-Agent'] = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.84 Safari/537.36"
    req = urllib.request.Request(url, data,  headers = headers)
    resp = urllib.request.urlopen(req)
    print("HERE")
    respData = resp.read()
    saveFile = open('withHeaders.txt', 'w')
    saveFile.write(str(respData))
    saveFile.close()
except Exception as e:
    print(e)

我猜错误在于req = urllib.request.Request(url,data,headers = headers)。什么是错误,语法?代码应该改变什么?任何概念上的错误都会纠正我。


编辑

概念:

def URLRequest(url, params, method="GET"):
    if method == "POST":
        return urllib2.Request(url, data=urllib.urlencode(params))
    else:
        return urllib2.Request(url + "?" + urllib.urlencode(params))
答案

您可以使用Requests库。它比urllib更清洁

import requests
q = 'Whatever you want to search'
url = 'https://www.google.com/search'
response = requests.get(url+'?'+'q='+q)
saveFile = open('response.txt', 'w')
savefile.write(response.text)
savefile.close()

或者如果你想坚持使用urllib,你可以这样做:

import urllib.request
url = 'https://www.google.com/search'
q = 'Search Query'
headers = {'User-Agent': "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.84 Safari/537.36"}
request = urllib.request.Request(url+'?'+'q='+q, headers=headers)
response = urllib.request.urlopen(request).read() # the text of the response is here
saveFile = open('withHeaders.txt', 'w')
saveFile.write(str(response))
saveFile.close()
另一答案

这里参考www.pythonforbeginners

# Importing the module
import urllib.request


# your search text
text="hi google"

# Define the url
url = 'http://www.google.com/#q='+text

# Add your headers
headers = {'User-Agent' : 'Mozilla 5.10'}

# Create the Request. 
request = urllib.request.Request(url, None, headers)

# Getting the response
response = urllib.request.urlopen(request)

# Print the headers
print (response.read())

以上是关于Python 3:HTTP错误405:不允许的方法的主要内容,如果未能解决你的问题,请参考以下文章

Django python联系电子邮件表单错误帖子不允许405

Flutter - 错误:不允许使用 HTTP 405 方法

405 方法不允许使用 $http 服务 AngularJS

REST - HTTP 状态 405;方法不允许;请求方法“PUT”不支持错误

HTTP 错误 405.0 - IIS Express 中不允许的方法

错误 HTTP/1.0 405 方法不允许