python确认dict(headers)包含一个特定的字符串

时间:2014-08-11 18:03:31

标签: python wordpress

我试图在Wordpress脚本中登录后在响应标题中找到一个字符串,所以我尝试使用这个find方法:

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'

是否有任何想法确认dict(标题)包含'wp-admin'或将dict(标题)转换为文本以正确使用find函数?

3 个答案:

答案 0 :(得分:0)

通常,要查找dict中包含字符串的所有项目:

[(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

答案 1 :(得分: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"

答案 2 :(得分:0)

首先,不要使用str.find()来测试子字符串的存在;请改为使用in会员资格测试:

>>> 'foo' in 'there was once a foo that barred a bar'
True
>>> 'foo' in 'spam, ham and eggs'
False

要测试字典的所有值中的子字符串,请遍历所有值。要仅测试存在,请对每个测试使用成员资格测试。带有生成器表达式的any() function通过循环只能找到匹配来提高效率:

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