简体   繁体   English

python 中从 urllib2 到 urllib3 的等效代码是什么

[英]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.课程中的示例使用 urllib2。 For some reason I can't get urllib2 but i have got urllib3.出于某种原因,我无法获得 urllib2,但我获得了 urllib3。 The code they have written is for urllib2 as shown below:他们编写的代码是针对 urllib2 的,如下所示:

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

When I write this out to do the same thing with urllib3 ie:当我写出来用 urllib3 做同样的事情时,即:

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

It gives me an error stating that the urllib3 module has no attribute 'Request'.它给了我一个错误,指出 urllib3 模块没有属性“请求”。

How then do i write the same bit of code but for urllib3?那么,除了 urllib3 之外,我如何编写相同的代码?

Cheer欢呼

To instantiate a Request object in urllib3, you're supposed to use the PoolManager() .要在 urllib3 中实例化 Request object,您应该使用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. Urllib2 和 Urllib3 有一些变化。您可以通过阅读文档来触摸它。 Sample code is below.示例代码如下。

This is a Urllib3 documentation Urllib3-Documentation这是一个 Urllib3 文档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.建议:如果您要开始新的东西,请通过原始文档 go。 :|) :|)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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