Python 3:HTTP错误405:不允许的方法 [英] Python 3 : HTTP Error 405: Method Not Allowed

查看:227
本文介绍了Python 3:HTTP错误405:不允许的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我收到"HTTP错误405:不允许使用方法"错误.我的代码是

I'm getting 'HTTP Error 405: Method Not Allowed' error. My code is

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,数据,标头=标头)中的错误.语法上有什么错误?代码中应更改什么?任何概念上的错误都会纠正我.

The error I guess is in req = urllib.request.Request(url, data, headers = headers). What is the error, syntactical? What should be changed in code? And any conceptual mistake do correct me.

编辑

概念:

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))

推荐答案

您可以使用请求库.它比urllib

You can use Requests library instead. It's much cleaner than 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,则可以执行以下操作:

Or if you want to stick to the urllib , you can do this:

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()

这篇关于Python 3:HTTP错误405:不允许的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆