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