gpt4 book ai didi

Python 3 : HTTP Error 405: Method Not Allowed

转载 作者:太空宇宙 更新时间:2023-11-03 14:20:56 30 4
gpt4 key购买 nike

我收到“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()

关于Python 3 : HTTP Error 405: Method Not Allowed,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47951270/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com