我正在使用下面的代码来检查服务器响应代码。我不想手动输入 URL,而是希望 python 检查 CSV ( data.csv
),然后将结果导出到新的 CSV ( new_data.csv
)。有谁知道怎么写这个?
谢谢你的时间!
import urllib2
for url in ["http://stackoverflow.com/", "http://stackoverflow.com/questions/"]:
try:
connection = urllib2.urlopen(url)
print connection.getcode()
connection.close()
except urllib2.HTTPError, e:
print e.getcode()
# Prints:
#200 or 404
更新:
import csv
out=open("urls.csv","rb")
data=csv.reader(out)
data=[row for row in data]
out.close()
print data
import urllib2
for url in ["http://stackoverflow.com/", "http://stackoverflow.com/questions/"]:
try:
connection = urllib2.urlopen(url)
print connection.getcode()
connection.close()
except urllib2.HTTPError, e:
print e.getcode()
输出:
[['link'], ['link'], ['link'], ['link'], ['link'], ['link']]
200
200
更新:
import csv
with open("urls.csv", 'r') as csvfile:
urls = [row[0] for row in csv.reader(csvfile)]
import urllib2
for url in urls:
try:
connection = urllib2.urlopen(url)
print connection.getcode()
connection.close()
except urllib2.HTTPError, e:
print e.getcode()