Python检查多个url能否正常运行

拖拉了2个月,个人项目终于开始动工,也在不断的学习和成长。手里拿到了一份OpenSources(github上直接搜索可以查到),感兴趣的朋友也可以下载csv文件进行练手。
import pandas as pd
import urllib.request
import time
#这里读取文件所在的位置
data =pd.read_csv('/Users/Macbook/Documents/GitHub/opensources/sources/sources.csv')
data[:30]#看一下前30行的数据是什么样的
#把pd中的一列写入fakenews.txt中
data['Unnamed: 0'].to_csv('fakenews.txt', sep='\t', index=False)


opener = urllib.request.build_opener()
opener.addheaders = [('User-agent', 'Mozilla/49.0.2')]
file = open('fakenews.txt')
lines = file.readlines()
checklist=[]
for line in lines:
    #这里注意一下:适用于爬虫和检测url有效性
    htp='http://'
    line = htp + line
    temp=line.replace('\n','')
    checklist.append(temp)
print(checklist)

print('测试:')
for a in checklist:
    tempUrl = a
    try :
        opener.open(tempUrl)
        print(tempUrl+'没问题')
        time.sleep(2)
    except urllib.error.URLError:
        print(tempUrl+'访问页面出错')
        time.sleep(2)
    # try except语句可以很好地帮助我们跳过错误,继续运行代码
    except Exception as e:
        print(a,e)
    time.sleep(1)
    #time模块能够避免被当作机器

Anyway Practice makes perfect
有任何问题可以相互交流,这里也要感谢@程序猿全敏提供的思路支持,本篇经验贴对其中经常报误的地方进行了修改和补充~

猜你喜欢

转载自blog.csdn.net/weixin_42294077/article/details/109385175