Python 使用 Urllib.Request 和 urlopen() 访问互联网
什么是 urllib?
urllib 是一个 Python 可用于打开 URL 的模块。它定义了一些函数和类来帮助执行 URL 操作。
通过 Python 您还可以访问和检索互联网数据,如 XML、HTML、JSON 等。您还可以使用 Python 直接处理这些数据。在本教程中,我们将了解如何从 Web 检索数据。例如,这里我们使用了 guru99 视频 URL,我们将使用 Python 以及打印该URL的HTML文件。
如何使用 Urllib 打开 URL
在运行代码连接互联网数据之前,我们需要导入URL库模块或“urllib”的语句。
- 导入 urllib
- 定义主要功能
- 声明变量 webUrl
- 然后调用URL lib库上的urlopen函数
- 我们打开的网址是 Youtube 上的 guru99 教程
- 接下来,我们将打印结果代码
- 通过调用我们创建的 webUrl 变量上的 getcode 函数来检索结果代码
- 我们将把它转换为字符串,以便它可以与我们的字符串“结果代码”连接起来
- 这将是一个常规的 HTTP 代码“200”,表示 http 请求已成功处理
如何获取 HTML 文件形式的 URL Python
您还可以使用“读取功能”来读取 HTML 文件 Python,当你运行代码时,HTML文件就会出现在控制台中。
- 调用 webURL 变量的读取函数
- 读取变量允许读取数据文件的内容
- 将 URL 的全部内容读入名为 data 的变量中
- 运行代码-它将把数据打印成 HTML 格式
以下是完整的代码
Python 2示例
# # read the data from the URL and print it # import urllib2 def main(): # open a connection to a URL using urllib2 webUrl = urllib2.urlopen("https://www.youtube.com/user/guru99com") #get the result code and print it print "result code: " + str(webUrl.getcode()) # read the data from the URL and print it data = webUrl.read() print data if __name__ == "__main__": main()
Python 3示例
# # read the data from the URL and print it # import urllib.request # open a connection to a URL using urllib webUrl = urllib.request.urlopen('https://www.youtube.com/user/guru99com') #get the result code and print it print ("result code: " + str(webUrl.getcode())) # read the data from the URL and print it data = webUrl.read() print (data)