您好,登錄后才能下訂單哦!
需求:Python檢測(cè)URL狀態(tài),并追加保存200的URL
代碼一:
#! /usr/bin/env python #coding=utf-8 import sys import requests def getHttpStatusCode(url): try: request = requests.get(url) httpStatusCode = request.status_code return httpStatusCode except requests.exceptions.HTTPError as e: return e if __name__ == "__main__": with open('1.txt', 'r') as f: for line in f: try: status = getHttpStatusCode(line.strip('\n'))#換行符 if status == 200: with open('200.txt','a') as f: f.write(line + '\n') print line else: print 'no 200 code' except Exception as e: print e
代碼二:
#! /usr/bin/env python # -*--coding:utf-8*- import requests def request_status(line): conn = requests.get(line) if conn.status_code == 200: with open('url_200.txt', 'a') as f: f.write(line + '\n') return line13 else: return None if __name__ == '__main__': with open('/1.txt', 'rb') as f: for line in f: try: purge_url = request_status(line.strip('\n')) except Exception as e: pass
代碼三:
#! /usr/bin/env python #coding:utf-8 import os,urllib,linecache import sys result = list() for x in linecache.updatecache(r'1.txt'): try: a = urllib.urlopen(x.replace('/n','')).getcode() #print x,a except Exception,e: print e if a == 200: #result.append(x) #保存 #result.sort() #排序結(jié)果 #open('2.txt', 'w').write('%s' % '\n'.join(result)) #保存入結(jié)果文件 with open ('200urllib.txt','a') as f: ## r只讀,w可寫,a追加 f.write(x + '\n') else: print 'error'
總結(jié)
以上所述是小編給大家介紹的python 檢測(cè)url 狀態(tài),希望對(duì)大家有所幫助,如果大家有任何疑問(wèn)請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)億速云網(wǎng)站的支持!
如果你覺(jué)得本文對(duì)你有幫助,歡迎轉(zhuǎn)載,煩請(qǐng)注明出處,謝謝!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。