如何在python 3中使用urllib?

穆斯

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

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

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

这是我的代码:

    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()
穆斯

幸运的是,我终于弄清楚了它的工作方式。这是我的代码:

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在我的情况下变量的类型为,<bytes>而不是<str>,因此要对其中的文本进行处理,我必须对其进行解码:

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

如何在Python 3中使用urllib中的basejoin

在Python 3中使用urllib检索文件(资源)的标题

如何在python中使用urllib3.PoolManager时设置代理

如何在python 2.7中使用urllib.request.urlretrieve

如何在Python中使用urllib来发布-Thingspeak.com中的API

在python 2.7中使用urllib3从url下载.txt文件?

如何在python中使用urllib下载.torrent文件?

如何在Spyder 3中使用Python 3?

如何在Python 3中使用wxPython?

如何在Python 3中使用Slugify?

如何在 OpenCV 3 中使用 Python 中的 PCACompute 函数?

如何在Python 3.4中使用pip 3?

如何在Python 3中使用PDFminer.six?

如何在python3中使用Asterisk AGI?

如何在Python 3中使用cmp()?

如何在Python 3中使用raw_input

如何在Python 3中使用input()读取文件

如何在Python 3中使用Turtle绘制Circle

我如何在sublimetext 3中使用python

如何在urllib中捕获404错误?(python 3)

如何在 Python 3 中使用 exit()

在Python3中使用Urllib下载文件,出现HTTP错误403-伪造用户代理?

如何在urllib2中使用SOCKS 4/5代理?

如何使用urllib 2在django-python 2.7中使用url下载和上传图像

如何在python中使用urllib2获取身份验证令牌?

如何在Python中使用urlopen或urllib2避免基于国家/地区的重定向

如何在python中使用urllib接收用户想要检索的文件的大小

如何在Python中使用urllib2发布本地文件?

使用urllib3模块而不是python中的请求