【轉載】Python2爬蟲之爬取某一路徑的所有html檔案

來源:互聯網
上載者:User

標籤:轉碼   正則表達   路徑   yii   開始   style   運算式   結構   odi   

 1 # -*- coding: UTF-8 -*-  2 import re 3 import urllib2 4  5 from collections import deque 6  7 # 儲存檔案的尾碼 8 SUFFIX=‘.html‘ 9 # 提取文章標題的Regex10 REX_TITLE=r‘<title>(.*?)</title>‘11 # 提取所需連結的Regex12 REX_URL=r‘/jdbc/(.+?).html‘13 # 種子url,從這個url開始爬取14 BASE_URL=‘http://www.yiibai.com/jdbc/‘15 16 17 # 將擷取到的文本儲存為html檔案18 def saveHtml(file_name,file_content):19 #    注意windows檔案命名的禁用符,比如 /20     with open(file_name.replace(‘/‘, ‘_‘)+SUFFIX,"wb") as f:21 #   寫檔案用bytes而不是str,所以要轉碼22         f.write(file_content)23 #   擷取文章標題24 def getTitle(file_content):25     linkre=re.search(REX_TITLE,file_content)26     if(linkre):27         print (‘擷取文章主題:‘+linkre.group(1))28         return linkre.group(1)29  30 #   爬蟲用到的兩個資料結構,隊列和集合31 queue=deque()32 visited=set()33 #   初始化種子連結 34 queue.append(BASE_URL)35 count=036  37 while queue:38     url=queue.popleft()  # 隊首元素出隊39     visited |= {url}  # 標記為已訪問40  41     print(‘已經抓取: ‘+ str(count)+‘   正在抓取 <---  ‘+url)42     count += 143     urlop=urllib2.urlopen(url)44 # 只處理html連結45     if ‘html‘ not in urlop.headers.getheader(‘Content-Type‘):46         continue47 # 避免程式異常中止48     try:49         data=urlop.read()50         title=getTitle(data).decode(‘utf-8‘);51     # 儲存檔案52         saveHtml(title,data)53     except:54         continue55  56 # Regex提取頁面中所有連結, 並判斷是否已經訪問過, 然後加入待爬隊列57     linkre = re.compile(REX_URL)58     for sub_link in linkre.findall(data):59         sub_url=BASE_URL+sub_link+SUFFIX;60 # 已經訪問過,不再處理61         if sub_url in visited:62             pass63         else:64         # 設定已訪問65             visited |= {sub_url}66         # 排入佇列67             queue.append(sub_url)68             print(‘join the quene--->  ‘+sub_url)

http://blog.csdn.net/wangshihui512/article/details/51100605#python

22 和 49行 與原文有所出處 如果添加了反而無法執行 可能和編碼有關係

【轉載】Python2爬蟲之爬取某一路徑的所有html檔案

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.