0

请有人将以下内容从python2转换为python3;

import requests

url = "http://duckduckgo.com/html"
payload = {'q':'python'}
r = requests.post(url, payload)
with open("requests_results.html", "w") as f:
f.write(r.content)

我明白了;

Traceback (most recent call last):
File "C:\temp\Python\testFile.py", line 1, in <module>
import requests
ImportError: No module named 'requests'

我也试过;

import urllib.request

url = "http://duckduckgo.com/html"
payload = {'q':'python'}
r = urllib.request.post(url, payload)
with open("requests_results.html", "w") as f:
f.write(r.content)

但我明白了

Traceback (most recent call last):
File "C:\temp\Python\testFile.py", line 5, in <module>
r = urllib.request.post(url, payload)
AttributeError: 'module' object has no attribute 'post'
4

3 回答 3

0

我认为这里的问题是没有安装 Requests 包。或者,如果您已安装它,它安装在您的 python2.x 目录中而不是 python3 中,这就是您无法使用 requests 模块的原因。尝试将 python3 作为默认副本,然后安装请求。

还可以尝试访问 Michael Foord 的这篇文章,它会引导您使用 urlib2 的所有功能

于 2013-05-18T14:57:57.477 回答
0

所以,在python3.2中,r.content是字节串,不是str,write不喜欢。您可能想改用 r.text :

with open("requests_results.html", "w") as f:
    f.write(r.text)

您可以在http://docs.python-requests.org/en/latest/api.html#main-interface的请求文档中看到它

class requests.Response
    content - Content of the response, in bytes.
    text - Content of the response, in unicode. if Response.encoding is None and chardet     module is available,

编码将被猜测。

编辑:

我在看到编辑后的问题之前发布了。是的,就像 Martijn Pieters 所说,您需要为 python3 安装 requests 模块才能导入它。

于 2013-05-17T15:34:27.983 回答
0
import urllib.request
import urllib.parse

url = "https://duckduckgo.com/html"
values = {'q':'python'}
data = urllib.parse.urlencode(values).encode("utf-8")

req = urllib.request.Request(url, data)
response = urllib.request.urlopen(req)
the_page = response.read()

print(the_page)
于 2018-07-05T12:07:03.097 回答