简体   繁体   中英

What is the equivalent code from urllib2 to urllib3 in python

I am new to coding and am following an online course. The example in the course uses urllib2. For some reason I can't get urllib2 but i have got urllib3. The code they have written is for urllib2 as shown below:

webRequest = urllib2.Request(urlofFilename,headers=hdr)

When I write this out to do the same thing with urllib3 ie:

webRequest = urllib3.Request(urlofFilename,headers=hdr)

It gives me an error stating that the urllib3 module has no attribute 'Request'.

How then do i write the same bit of code but for urllib3?

Cheer

To instantiate a Request object in urllib3, you're supposed to use the PoolManager() . You'll pass headers as additional request data :

http = urllib3.PoolManager()
webRequest = http.request('GET', urlofFilename, headers={'key': value})

Urllib2 and Urllib3 has some changes.You can touch it by reading documentation. Sample code is below.

This is a Urllib3 documentation Urllib3-Documentation

import urllib3

http = urllib3.PoolManager()
r = http.request('POST', 'https://urllib3.readthedocs.io/en/latest/user-guide.html')
print(r.status)
  • Advice: if you are starting something newly please go thru the original documentation. :|)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM