简体   繁体   English

自定义打开器或请求标头

[英]Custom opener or Request headers

I am trying to replicate a wget command in a Python script. 我正在尝试在Python脚本中复制wget命令。 The wget command goes along these lines: wget命令遵循以下几行:

wget --user user --password pass http://serveraddress/

FYI, and as you can guess, it's a simple authentication which is mandatory. 仅供参考,您可以猜到,这是强制性的简单身份验证。 You are prompted with a pop up form where you enter your username and password. 系统会提示您一个弹出表单,您可以在其中输入用户名和密码。 So, unless you enter the credentials you can't reach the address. 因此,除非您输入凭据,否则您将无法到达地址。
In my script, I prompt the user to enter his username and password and I store them. 在我的脚本中,提示用户输入用户名和密码并将其存储。 So far everything makes sense. 到目前为止,一切都有意义。 However, after this I get really confused. 但是,在此之后,我感到非常困惑。 The reason is that I read two different things on the web in general and in fact in Python Essential Reference about urllib2.urlopen() (FYI, I have to use the standard library only; so requests is not an option for me). 原因是,我通常在网上阅读了两种不同的东西,实际上是在《 Python基本参考》中关于urllib2.urlopen()的内容(FYI,我只需要使用标准库;因此,请求不是我的选择)。
So, PER says “The basic urlopen() function does not provide support for authentication, cookies, or other advanced features of HTTP. 因此,PER表示“基本的urlopen()函数不提供对身份验证,cookie或HTTP的其他高级功能的支持。 To add support, you must create your own custom opener object using the build_opener() function.” Other people, for example here , say that you need to create a Request object and add headers to it. 要增加支持,必须使用build_opener()函数创建自己的自定义打开器对象。”其他人,例如在这里 ,说您需要创建一个Request对象并向其添加标头。 So, what am I missing here? 那么,我在这里想念什么? Any help is much appreciate. 任何帮助都非常感谢。

Use the requests package. 使用requests包。 Your question is, in fact, the very first example they cite in their doc: 实际上,您的问题是他们在文档中引用的第一个示例:

r = requests.get('https://api.github.com/user', auth=('user', 'pass'))

However, if you absolutely cannot use requests , the authors conveniently describe how to use the equivalent functionality in urllib2 . 但是,如果您绝对不能使用requests ,则作者可以方便地描述如何使用urllib2的等效功能。 Go to the requests documentation page , click on "See similar code, without Requests ", and steal the urllib2 code from there. 转到requests文档页面 ,单击“查看类似的代码,但没有请求 ”,然后从那里窃取urllib2代码。

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

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