如何在python中使用urllib?

时间:2019-02-02 12:37:28

标签: python urllib

我想知道是否有人可以帮助我使我的代码正常工作。

import urllib.request
import urllib.parse
import re

url = 'https://www.google.com'
values = {'s':'basics',
      'submit':'search'}
data = urllib.parse.urlencode(values)
data = data.encode('utf-8')
req = urllib.request.Request(url,data)
resp = urllib.request.urlopen(req)
respData = resp.read()

print(respData)

运行代码时,它会向我显示此错误消息。

TypeError: POST data should be bytes, an iterable of bytes, or a file object. It cannot be of type str.

我希望有人可以帮助我解决我的问题。如果不是,还是要谢谢。

它给了我这个巨大的错误信息:

It is giving me this gigantic error    
Traceback (most recent call last):
File "C:\Users\user\OneDrive\Desktop\Lotto.py", line 11, in <module>
resp = urllib.request.urlopen(req)
File "C:\Users\user\AppData\Local\Programs\Python\Python37-32\lib\urllib   \request.py", line 222, in urlopen
return opener.open(url, data, timeout)
File "C:\Users\user\AppData\Local\Programs\Python\Python37-32\lib\urllib\request.py", line 531, in open
response = meth(req, response)
File "C:\Users\user\AppData\Local\Programs\Python\Python37-32\lib\urllib\request.py", line 641, in http_response
'http', request, response, code, msg, hdrs)
File "C:\Users\user\AppData\Local\Programs\Python\Python37-32\lib\urllib\request.py", line 569, in error
return self._call_chain(*args)
File "C:\Users\user\AppData\Local\Programs\Python\Python37-32\lib\urllib\request.py", line 503, in _call_chain
result = func(*args)
File "C:\Users\user\AppData\Local\Programs\Python\Python37-32\lib\urllib\request.py", line 649, in http_error_default
raise HTTPError(req.full_url, code, msg, hdrs, fp)
urllib.error.HTTPError: HTTP Error 405: Method Not Allowed

1 个答案:

答案 0 :(得分:0)

由于您有TYPO,因此无法正常工作

data = urllib.parse.urlencode(values)
date = data.encode('utf-8') # YOUR TYPO IS HERE
req = urllib.request.Request(url,data)

您需要将该行更改为:

data = data.encode('utf-8') # TYPO FIXED!