我目前正在使用python 2.7在其源代碼中爲多個關鍵字搜索網站。我想分配和出口這些關鍵字來單獨列在導出CSV文件是這樣的:如何使用python將多列寫入CSV標頭?
然而,我的代碼我得到這個:
我代碼:
import urllib2
import csv
fieldnames = ['Website', 'Sitemap', 'Viewport', '@media']
def csv_writerheader(path):
with open(path, 'w') as csvfile:
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
writer.writeheader()
def csv_writer(domainname,Sitemap, path):
with open(path, 'a') as csvfile:
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
# writer.writeheader()
writer.writerow({'Website': domainname, 'Sitemap': Sitemap})
csv_output_file = 'exported_print_results.csv'
keyword1 = ['sitemap']
keyword2 = ['viewport']
keyword3 = ['@media']
csv_writerheader(csv_output_file)
f = open('top1m-edited.csv')
csv_f = csv.reader(f)
for line in f:
strdomain = line.strip()
if '.nl' in strdomain:
try:
req = urllib2.Request(strdomain.strip())
response = urllib2.urlopen(req)
html_content = response.read()
# keyword 1
for searchstring in keyword1:
if searchstring.lower() in str(html_content).lower():
print (strdomain, keyword1, 'found')
csv_writer(strdomain, 'found', csv_output_file)
else:
print (strdomain, keyword1, 'not found')
csv_writer(strdomain, 'not found', csv_output_file)
# keyword 2
for searchstring in keyword2:
if searchstring.lower() in str(html_content).lower():
print (strdomain, keyword2, 'found')
csv_writer(strdomain, 'found', csv_output_file)
else:
print (strdomain, keyword2, 'not found')
csv_writer(strdomain, 'not found', csv_output_file)
# keyword 3
for searchstring in keyword3:
if searchstring.lower() in str(html_content).lower():
print (strdomain, keyword3, 'found')
csv_writer(strdomain, 'found', csv_output_file)
else:
print (strdomain, keyword3, 'not found')
csv_writer(strdomain, 'not found', csv_output_file)
except urllib2.HTTPError:
print (strdomain, 'HTTP ERROR')
except urllib2.URLError:
print (strdomain, 'URL ERROR')
except urllib2.socket.error:
print (strdomain, 'SOCKET ERROR')
except urllib2.ssl.CertificateError:
print (strdomain, 'SSL Certificate ERROR')
f.close()
我該如何編輯我的代碼才能使其工作?
謝謝你,它的工作原理! – jakeT888