Urllib的使用和实例代码

什么是Rullib?

    Python内置的http请求库

发送请求

  1. """ 
  2. urllib.request模块提供了人最基本的构造http请求的方法,利用它可以模拟浏览器的一个发起过程 
  3. """  
  4. #案例1  
  5. if __name__ == '__main__':  
  6.     import urllib.request  
  7.     import socket  
  8.     import urllib.error  
  9.     try:  
  10.         response = urllib.request.urlopen("http://www.python.org",timeout=0.1)  
  11.     except urllib.error.URLError as e:  
  12.         if isinstance(e.reason,socket.timeout):  
  13.             print("TIME OUT")  
  14.     print(response.read().decode('utf8'))#返回网页源代码,得到源代码之后,其中的信息就能很好的提起出来了  
  15.     print(type(response))#返回相应类型  
  16.     print(response.status)#返回响应状态码  
  17.     print(response.getheaders())#获取响应头  
  18.     print(response.getheader('Server'))#获取响应头中的一部分内容  
  19. """ 
  20. 其他的参数: 
  21. data: 可选参数,如果使用该方法,则请求方式改为POST 
  22. timeout: 用于设置超时时间,单位为秒,如果不指定,则使用全局默认时间 
  23. """  

猜你喜欢

转载自www.cnblogs.com/songdongdong6/p/10294671.html