如何在python 3中使用带有用户名/密码身份验证的urllib?

如何在python 3中使用带有用户名/密码身份验证的urllib?

问题描述:

这是我在 python 3 中使用 urllib 的问题.

Here is my problem with urllib in python 3.

我写了一段在 Python 2.7 中运行良好的代码,并且正在使用 urllib2.它转到 Internet 上的页面(需要授权)并从该页面获取信息.

I wrote a piece of code which works well in Python 2.7 and is using urllib2. It goes to the page on Internet (which requires authorization) and grabs me the info from that page.

对我来说真正的问题是我不能让我的代码在 python 3.4 中工作,因为没有 urllib2,而且 urllib 的工作方式不同;即使经过几个小时的谷歌搜索和阅读,我也一无所获.因此,如果有人能帮我解决这个问题,我将非常感谢您的帮助.

The real problem for me is that I can't make my code working in python 3.4 because there is no urllib2, and urllib works differently; even after few hours of googling and reading I got nothing. So if somebody can help me to solve this, I'd really appreciate that help.

这是我的代码:

    request = urllib2.Request('http://mysite/admin/index.cgi?index=127')
    base64string = base64.encodestring('%s:%s' % ('login', 'password')).replace('\n', '')
    request.add_header("Authorization", "Basic %s" % base64string)
    result = urllib2.urlopen(request)
    resulttext = result.read()

感谢你们,我终于找到了它的工作方式.这是我的代码:

Thankfully to you guys I finally figured out the way it works. Here is my code:

request = urllib.request.Request('http://mysite/admin/index.cgi?index=127')
base64string = base64.b64encode(bytes('%s:%s' % ('login', 'password'),'ascii'))
request.add_header("Authorization", "Basic %s" % base64string.decode('utf-8'))
result = urllib.request.urlopen(request)
resulttext = result.read()

毕竟,urllib 还有一个不同之处:在我的例子中,resulttext 变量的类型是 而不是 ;,所以要对其中的文本进行处理,我必须对其进行解码:

After all, there is one more difference with urllib: the resulttext variable in my case had the type of <bytes> instead of <str>, so to do something with text inside it I had to decode it:

text = resulttext.decode(encoding='utf-8',errors='ignore')