Python 列表 - 如何使用带有 dns.resolver.query for 循环的域列表

Python Lists - How do I use a list of domains with dns.resolver.query for loop

print (data[1])
ymcacanada.ca

answers = dns.resolver.query(data[1]), 'MX')
traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "dns\resolver.py", line 981, in query
File "dns\resolver.py", line 912, in query
File "dns\resolver.py", line 143, in __init__
dns.resolver.NoAnswer

我希望数据[1]等于"ymcacanada",所以我可以在for循环中调用整个数据列表,dns.resolver查找MX记录。

我得到的是这个错误,当我手动 运行 带有 url 的代码时不会发生这个错误。

接下来我要做的是将这些查找写入 .CSV

到目前为止,这是我的代码(不起作用!)

import dns
import dns.resolver
import os
import csv
import dns.resolver

file = "domains.txt"
f = open(file)
data = f.read()
f.close
list = []

for url in data:
    answers = dns.resolver.query(url, 'MX')
    for rdata in answers:
        x = [rdata.exchange, rdata.preference]
        print(x)
        list.append([x])

编辑

嘿,这里是我的全部工作代码。我确信它可以改进,但我仍在学习!

import dns
import dns.resolver
import os
import csv

##tested on python 2.7 only

errcountA = 0
errcountMX = 0
listoflists = []

with open("domains.txt") as f:
    for url in f:
        A = []
        MX = []
        url = url.strip()
        try: 
            answers = dns.resolver.query(url, 'A') ##Get the A record
            for rdata in answers:
                A.append(rdata.address) ## Add A Records to list
        except: ## Incase the URL doesnt resolve
            A = "Error resolving"
            errcountA += 1

        try: ##Get the MX record
            answers = dns.resolver.query(url, 'MX')
            for rdata in answers:
                MX.append([rdata.preference, rdata.exchange])

        except: ##incase url doesnt resolver
            MX = "Error resolving"
            errcountMX += 1

        list = [url, MX, A]
        print(list)
        listoflists.append(list)

with open('output.csv', 'wb') as csvfile: ##write the csv file
    writer = csv.writer(csvfile)
    for r in listoflists:
        writer.writerow(r)

print listoflists
print ("There were %e A record errors") %errcountA
print ("There were %f MX record errors") %errcountMX
print ("Done!")

您的 url 数据包括尾随换行符。使用 .strip() 从数据中删除任何前导或尾随空格。试试这个:

with open("domaints.txt") as f:
    for url in f:
        url = url.strip()
        answers = dns.resolver.query(url, 'MX')
        # Continue as before