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

2024-04-19 05:33:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我尝试在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'

有没有办法确认dict(headers)包含“wp admin”或将dict(headers)转换为文本以正确使用find函数?你知道吗


Tags: in脚本ifadminresponsewordpressresfind
3条回答

首先,不要使用str.find()测试是否存在子字符串;而是使用in成员身份测试:

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

要测试字典的all值中的子字符串,请对所有值进行循环。为了测试是否存在,对每一个都使用成员资格测试。带有生成器表达式的^{} function通过循环仅足以找到匹配项,使其更高效:

if any('wp-admin' in v for v in response.headers.itervalues()):

这里^{}在循环时懒洋洋地产生字典中的所有值。你知道吗

但是,对于请求头,我通常希望值仅显示在一个头中;您最好查找特定的头:

if 'wp-admin' in response.headers.get('set-cookie', ''):

其中,如果Set-Cookie头不存在,.get()方法将返回''。你知道吗

错误消息告诉您,数据类型dict与其他数据类型一样,没有可用的find方法。但对你来说好消息是响应.标题已经在一个字典一样的格式,所以你可以直接搜索你的“wp管理员”。你知道吗

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"

通常,要在dict中查找值包含字符串的所有项,请执行以下操作:

[(key, value) for (key, value) in the_dict.items() if search_string in value]

(在Python2.x上,使用iteritems提高效率。)

如果你只需要知道它是否存在:

any(search_string in value for value in the_dict.values())

(在python2.x上也可以使用itervalues

相关问题 更多 >