拖拉了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
有任何問題可以相互交流,這里也要感謝@程式猿全敏提供的思路支持,本篇經驗貼對其中經常報誤的地方進行了修改和補充~
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/197080.html
標籤:其他
