亿迅智能制造网
工业4.0先进制造技术信息网站!
首页 | 制造技术 | 制造设备 | 工业物联网 | 工业材料 | 设备保养维修 | 工业编程 |
home  MfgRobots >> 亿迅智能制造网 >  >> Industrial programming >> Python

使用 Urllib.Request 和 urlopen() 的 Python Internet 访问

什么是urllib?

urllib 是一个 Python 模块,可用于打开 URL。它定义了函数和类来帮助 URL 操作。

使用 Python,您还可以从 Internet 访问和检索数据,例如 XML、HTML、JSON 等。您还可以使用 Python 直接处理这些数据。在本教程中,我们将了解如何从 Web 中检索数据。例如,这里我们使用了一个 guru99 视频 URL,我们将使用 Python 访问这个视频 URL 并打印这个 URL 的 HTML 文件。

在本教程中,我们将学习

如何使用 Urllib 打开 URL

在我们运行代码连接互联网数据之前,我们需要为 URL 库模块或“urllib”导入语句。

如何在 Python 中获取 HTML 文件形式的 URL

也可以使用Python中的“读取函数”读取HTML文件,运行代码时,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)

Python

  1. 使用 SaaS 和云需要仔细的数据整理
  2. Python 关键字和标识符
  3. Python 语句、缩进和注释
  4. Python 变量、常量和文字
  5. Python 数据类型
  6. Python 类型转换和类型转换
  7. Python 输入、输出和导入
  8. Python 全局、局部和非局部变量
  9. Python 目录和文件管理
  10. Python 错误和内置异常
  11. Python 异常处理使用 try、except 和 finally 语句
  12. Python 和 Raspberry Pi 温度传感器