如何使用urlopen方法获取HTTP资源?

请问如何使用urlopen方法获取HTTP资源?具体操作起来复杂吗?

urlopen 方法是 Python 中的一种内置方法,可以用于获取 HTTP 资源。它位于 urllib.request 模块中,使用起来非常简单,只需要几行代码即可完成。
下面是一个简单的示例,展示了如何使用 urlopen 方法获取一个网页的内容:

import urllib.request

# 设置 URL
url = "http://www.example.com"

# 打开 URL,并获取返回值
response = urllib.request.urlopen(url)

# 读取返回值
html = response.read()

# 将返回值转换为字符串
html = html.decode()

# 打印结果
print(html)

上面的代码中,我们首先调用 urllib.request.urlopen 方法打开了一个 URL,然后调用 read 方法读取返回值,最后使用 decode 方法将返回值转换为字符串。