html=req.read().decode('gb18030')
# bytes object
b = b"example"# str object
s = "example"
# str to bytes
bytes(s, encoding = "utf8")
# bytes to str
str(b, encoding = "utf-8")
# an alternative method
# str to bytes
str.encode(s)
# bytes to str
bytes.decode(b)
import urllib2
content = urllib2.urlopen('http://XXXX').read()
代理服务器:
import urllib2
proxy_support = urllib2.ProxyHandler({'http':'http://XX.XX.XX.XX:XXXX'})
opener = urllib2.build_opener(proxy_support, urllib2.HTTPHandler)
urllib2.install_opener(opener)
content = urllib2.urlopen('http://XXXX').read()
cookie的处理:
import urllib2, cookielib
cookie_support= urllib2.HTTPCookieProcessor(cookielib.CookieJar())
opener = urllib2.build_opener(cookie_support, urllib2.HTTPHandler)
urllib2.install_opener(opener)
content = urllib2.urlopen('http://XXXX').read()
同时使用代理和cookie;
opener = urllib2.build_opener(proxy_support, cookie_support, urllib2.HTTPHandler)
Python 一般字符串变量如何转化为 raw string
我看到大部分raw string都是通过对字符串常量前面加个r来定义,
有没有转化为raw string的函数呢?
如果我有个一般字符串变量,怎么才能把这个变量转为raw string?
找了半天,似乎没有这种需求,很奇怪
谢谢!
------解决方案--------------------------------------------------------
有些字符打不出来或显不出来,所以使用转义符方式让人看得明白是有个东西在那儿,但是这个是文本代码里的字符面值要变成内部数据时才发生转变,已经是内部数据就没再进行转义,也就没所谓raw不raw的区别。
如果因某种错误需要修复,可以试试用eval()或repr()处理一下...
>>> a = '\\123'
>>> print a
\123
>>> a = repr(a)[1:-1]
>>> print a
\\123
>>> a = eval("'%s'" % a)
>>> print a
\123
mport:
import http.client
因为HTTPConnection是在http.client下面的。因为装的是python3,猜想是新的python有些名字改了,在google上一找,果然如此,和http相关的有这几个对应关系:
httplib -> http.client
Cookie -> http.cookies
cookielib -> http.cookiejar
BaseHTTPServer -> http.server
SimpleHTTPServer -> http.server
CGIHttpServer -> http.server
这个地址是关于python2到python3 port的一些变化:
http://diveintopython3.org/porting-code-to-python-3-with-2to3.html