python如何爬取网站所有目录_[python] 爬取网站所有的URL
運(yùn)行python腳本,最終程序目錄下會(huì)是這樣:
result.txt中保存所有的URL
文件夾sh.neusoft.com中保存爬蟲(chóng)得到的所有網(wǎng)頁(yè)
main.py的源代碼如下
# -*- coding: utf-8 -*
import os
import re
import shutil
REJECT_FILETYPE = 'rar,7z,css,js,jpg,jpeg,gif,bmp,png,swf,exe'#定義爬蟲(chóng)過(guò)程中不下載的文件類型
def getinfo(webaddress):
global REJECT_FILETYPE
url = 'http://'+webaddress+'/'#通過(guò)用戶輸入的網(wǎng)址連接上網(wǎng)絡(luò)協(xié)議,得到URL。
print 'Getting>>>>> '+url#打印提示信息,表示正在抓取網(wǎng)站
websitefilepath = os.path.abspath('.')+'/'+webaddress#通過(guò)函數(shù)os.path.abspath得到當(dāng)前程序所在的絕對(duì)路徑,然后搭配用戶所輸入的網(wǎng)址得到用于存儲(chǔ)下載網(wǎng)頁(yè)的文件夾
if os.path.exists(websitefilepath):#如果此文件夾已經(jīng)存在就將其刪除,原因是如果它存在,那么爬蟲(chóng)將不成功
shutil.rmtree(websitefilepath)#shutil.rmtree函數(shù)用于刪除文件夾(其中含有文件)
outputfilepath = os.path.abspath('.')+'/'+'output.txt'#在當(dāng)前文件夾下創(chuàng)建一個(gè)過(guò)渡性質(zhì)的文件output.txt
fobj = open(outputfilepath,'w+')
command = 'wget -r -m -nv --reject='+REJECT_FILETYPE+' -o '+outputfilepath+' '+url#利用wget命令爬取網(wǎng)站
tmp0 = os.popen(command).readlines()#函數(shù)os.popen執(zhí)行命令并且將運(yùn)行結(jié)果存儲(chǔ)在變量tmp0中
print >> fobj,tmp0#寫(xiě)入output.txt中
allinfo = fobj.read()
target_url = re.compile(r'\".*?\"',re.DOTALL).findall(allinfo)#通過(guò)正則表達(dá)式篩選出得到的網(wǎng)址
target_num = len(target_url)
fobj1 = open('result.txt','w')#在本目錄下創(chuàng)建一個(gè)result.txt文件,里面存儲(chǔ)最終得到的內(nèi)容
for i in range(target_num):
print >> fobj1,target_url[i][1:-1]
fobj.close()
fobj1.close()
if os.path.exists(outputfilepath):#將過(guò)渡文件output.txt刪除
os.remove(outputfilepath)#os.remove用于刪除文件
if __name__=="__main__":
webaddress = raw_input("Input the Website Address(without \"http:\")>")
getinfo(webaddress)
print "Well Done."#代碼執(zhí)行完畢之后打印此提示信息
完事兒
與50位技術(shù)專家面對(duì)面20年技術(shù)見(jiàn)證,附贈(zèng)技術(shù)全景圖總結(jié)
以上是生活随笔為你收集整理的python如何爬取网站所有目录_[python] 爬取网站所有的URL的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: sql count(1) count(*
- 下一篇: python redis 人员信息查询_