Python确认字典(headers)包含特定字符串
我正在尝试在Wordpress脚本登录后的响应头中找到一个字符串,所以我用了这个查找方法:
import urllib, urllib2, os, sys, requests , re
....
....
req = urllib2.Request(url, urllib.urlencode(dict(data)), dict(headers))
response = urllib2.urlopen(req)
res = dict(response.headers)
res1 = 'wp-admin'
if res.find(res1) >= 0:
print 'wp-admin exist in dict(response.headers)'
但是我遇到了这个错误:
Traceback (most recent call last):
File "C:\Python27\wp2\wp12.py", line 29, in <module>
if res.find(res1) >= 0:
AttributeError: 'dict' object has no attribute 'find'
有没有什么办法可以确认字典(headers)中包含'wp-admin',或者把字典(headers)转换成文本,以便正确使用查找函数?
3 个回答
0
这个错误信息告诉你,dict这种数据类型没有像其他数据类型那样的find方法。不过好消息是,response.headers已经是类似字典的格式,所以你可以直接查找你的“wp-admin”。
import urllib2
url = "http://www.google.com"
response = urllib2.urlopen(url)
for headername in response.headers:
print headername, response.headers[headername]
if "wp-admin" in response.headers:
print "header found"
其实也可以这样理解:
a = {"wp-admin":"value1",
"header2":"value2"}
if "wp-admin" in a:
print "Found header"
0
首先,不要用 str.find()
来检查一个子字符串是否存在;应该用 in
来做这个检查,这样更简单。
>>> 'foo' in 'there was once a foo that barred a bar'
True
>>> 'foo' in 'spam, ham and eggs'
False
如果你想在字典的所有值中查找一个子字符串,可以遍历所有的值。要检查某个值是否存在,可以对每个值进行检查。使用 any()
函数 和生成器表达式,这样会更高效,因为它只会循环到找到匹配为止:
if any('wp-admin' in v for v in response.headers.itervalues()):
这里的 dict.itervalues()
在遍历时会懒惰地返回字典中的所有值。
不过,对于请求头,我通常会期待某个值只出现在一个特定的头里;所以你最好直接查找那个特定的头:
if 'wp-admin' in response.headers.get('set-cookie', ''):
在这里,.get()
方法会返回 ''
,如果 Set-Cookie
头不存在的话。
0
一般来说,如果你想在一个字典中找到所有值包含某个字符串的项,可以这样做:
[(key, value) for (key, value) in the_dict.items() if search_string in value]
(在Python 2.x中,为了提高效率,可以使用 iteritems
。)
如果你只想知道这个字符串是否存在:
any(search_string in value for value in the_dict.values())
(在Python 2.x中,你也可以使用 itervalues
。)