将带有反斜杠字符的变量添加到URL字符串时出现Python错误

时间:2017-06-26 14:10:14

标签: python url cookies urllib2 backslash

我正在尝试从分配会话cookie的网站上抓取一些数据,并生成包含碎屑代码的HTML,我需要将其附加到URL以获取数据。当crumb变量包含反斜杠时,我遇到了问题(HTTP 401 Unauthorized)...由于crumb是一个变量,我无法弄清楚如何将r'添加到开头。我尝试将.encode('string-escape')和.replace('\\','\\\\')添加到crumb变量中,但我无法使其工作。

我的代码,在python 2.7中,看起来像这样:

cj = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))    
opener.open('http://www.sample.com')

#Some code here that looks for crumb code in HTML

crumb = 'abc\xyz'

#This line fails when crumb contains a backslash
opener.open('http://www.sample.com/data=' + crumb)

cj.clear()

有没有人知道在尝试打开包含反斜杠的网址字符串时如何避免401错误?

此外,如果我循环使用多个面包屑,是否有必要每次都清除会话cookie?

更新:事实证明,反斜杠是从HTML中的\ u002F引入的。我相信如果我在将字符串添加到URL之前将它们转换为正斜杠,它将起作用。如何将字符串中的\ u002F转换为/?

2 个答案:

答案 0 :(得分:0)

这里的问题是“\”是python中的转义字符,因此要使其成为不包含任何特殊字符的原始字符串,必须在字符串之前添加“r”。您的代码应如下所示

cj = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))    
opener.open('http://www.sample.com')

#I'm adding a 'r' before the string

crumb = r'abc\xyz'

opener.open('http://www.sample.com/data=' + crumb)

cj.clear()

编辑:您可能必须对“\”进行编码才能正确格式化网址请求。所以“\”将是“%5C”。

答案 1 :(得分:0)

由于您无法使用crumb = r'abc\xyz'。我相信str.encode('string-escape')功能可能有所帮助。尝试:

crumb = 'abc\xyz'
crumb.encode('string-escape')