我试图直接从MYSQLDB
表和tldextract
中读取URL,以便从URL中获取域,并找到域的SPF(Sender Policy Framework)记录。你知道吗
当我试图写我扫描的每个域的SPF记录时,我的Ouput_SPF_Records.txt
不包含我写的任何记录。你知道吗
对这个问题不确定,有什么建议吗?你知道吗
import sys
import socket
import dns.resolver
import re
import MySQLdb
import tldextract
from django.utils.encoding import smart_str, smart_unicode
def getspf (domain):
answers = dns.resolver.query(domain, 'TXT')
for rdata in answers:
for txt_string in rdata.strings:
if txt_string.startswith('v=spf1'):
return txt_string.replace('v=spf1','')
db=MySQLdb.connect("x.x.x.x","username","password","db_table")
cursor=db.cursor()
cursor.execute("SELECT application_id,url FROM app_info.app_urls")
data=cursor.fetchall()
x=0
while x<len(data):
c=tldextract.extract(data[x][1])
#print c
app_id=data[x][0]
#print app_id
d=str(app_id)+','+c[1]+'.'+c[2]
#with open('spfout.csv','a') as out:
domain=smart_str(d)
#print domain
with open('Ouput_SPF_Records.txt','w') as g:
full_spf=""
spf_rec=""
y=domain.split(',')
#print "y===",y,y[0],y[1]
app_id=y[0]
domains=y[1]
try:
full_spf=getspf(domains.strip())+"\n"
spf_rec=app_id+","+full_spf
print spf_rec
except Exception:
pass
g.write(spf_rec)
x=x+1
g.close()
你的问题是你打开文件很多次,每次都是通过循环。使用
w
模式,从一开始就删除内容和写入。你知道吗要么在循环之前打开一次文件,要么以附加模式
a
打开,这样就不会删除以前写入的数据。你知道吗尝试用append模式而不是
w
模式打开文件。w
模式在每次迭代中覆盖文件。示例-最可能的情况是,上次以写模式打开文件时,您没有在中写入任何内容,因为您正在捕获并忽略所有异常,这会导致空文件。你知道吗
另外,如果知道预期的错误,应该使用
except <Error>:
而不是except Exception:
。示例-您可以使用:
调试代码并尝试找出问题所在。 还要注意: 1你不应该只在try/except块中写“pass”。处理例外情况
2。你知道吗
它将自动关闭文件,因此无需显式执行:g.close()。你知道吗
相关问题 更多 >
编程相关推荐