官术网_书友最值得收藏!

With Python 3

In Python 3 both urllib and urllib2 are part of the urllib module, so there is some difference in using urllib. Also, the urllib package contains the following modules:

  • urllib.request
  • urllib.error
  • urllib.parse
  • urllib.robotparser

The urllib.requestmodule is used for opening and fetching URLs with Python 3:

  1. First import the urllib.request module from urllib packages:
>>> import urllib.request
  1. Get the web page with the urlopen method:
>>> webpage = urllib.request.urlopen("https://www.packtpub.com/")  
  1. Read the object with the read method:
>>> source =  webpage.read()  
  1. Close the object:
>>> webpage.close()  
  1. Print the source:
>>> print(source)  
  1. You can write the contents of the source string to a local file on your computer as follows. Make sure that the output file is in binary mode:
>>> f = open('packtpub-home.html', 'wb')
      >>> f.write(source)
      >>> f.close  

Python 2 modules urllib and urllib2 help to do URL-request-related stuff, but both have different functionalities.
urllib provides the urlencode method, which is useful in generating GET requests. However, urllib2 doesn't support the urlencode method. Also, urllib2 can accept the request object and modify the headers for a URL request, but urllib can only accept the URL and is not capable of modifying the headers in it.

主站蜘蛛池模板: 广西| 墨脱县| 南岸区| 克拉玛依市| 襄汾县| 天台县| 蒙阴县| 平遥县| 都兰县| 镇原县| 北碚区| 博野县| 五家渠市| 苍溪县| 通河县| 吴忠市| 北流市| 丰城市| 桐庐县| 安图县| 墨竹工卡县| 乌鲁木齐县| 开鲁县| 禹城市| 县级市| 泰兴市| 郧西县| 白河县| 定远县| 双桥区| 镇赉县| 厦门市| 大冶市| 内江市| 伊宁县| 民丰县| 奇台县| 都昌县| 墨竹工卡县| 宿迁市| 彩票|