Python資料擷取-開始爬蟲

來源:互聯網
上載者:User

標籤:採集   date   pip   ide   資料資訊   parse   font   test   png   

一 遍曆單個網域名稱

網頁爬蟲,就是對目標網頁進行捉取,然後遍曆到資料資訊,然後有連結的繼續遍曆,如此回調。

第一步:將頁面的所有連結擷取

 1 from urllib.request import urlopen 2 from bs4 import BeautifulSoup 3 import  re 4  5 html = urlopen("https://www.yahoo.com/") 6 html_str = html.read().decode(‘utf-8‘) 7 #print(html_str) 8 bsObj = BeautifulSoup(html_str) 9 ##擷取頁面連結地址10 for link in bsObj.findAll("a"):11     if ‘href‘ in link.attrs:12         print(link.attrs[‘href‘])

運行

發現會存在些沒用用的資料,有些href的值只是作為頁面塊的跳轉,我們可以使用Regex進行最佳化過濾掉,只擷取帶有HTML結尾的連結

 1 from urllib.request import urlopen 2 from bs4 import BeautifulSoup 3 import  re 4  5 html = urlopen("https://www.yahoo.com/") 6 html_str = html.read().decode(‘utf-8‘) 7 #print(html_str) 8 bsObj = BeautifulSoup(html_str) 9 ##擷取頁面連結地址10 for link in bsObj.findAll("a" ,href= re.compile(".*\.html")):11     if ‘href‘ in link.attrs:12         print(link.attrs[‘href‘])

 

 第二步:遞迴擷取網頁

第一步我們基本把一個網頁的所有連結地址擷取到,第二步顯然是擷取這些連結網頁的連結,進一步擷取這些網頁資料。

例如我們在Wiki擷取Python詞條下面的相關詞條的連結,由於存在不是我們關心的連結,所有需要Regex過濾掉一部分,然後大量的連結的連結的連結,我們不可能窮盡,所有隨機擷取一些詞條。

 1 from urllib.request import urlopen 2 from bs4 import BeautifulSoup 3 import  re 4 import  datetime 5 import random 6  7 rd = random.seed(datetime.datetime.now()) 8 print(rd) 9 10 def getLinks(articleUrl):11     html = urlopen("https://en.wikipedia.org"+articleUrl)12     bsObj = BeautifulSoup(html,"lxml")13     return bsObj.findAll("a",href=re.compile("^(/wiki/)((?!:).)*$"))14 15 links = getLinks("/wiki/Python")16 17 while len(links) >0 :18     #print(links)19     newArticle = links[random.randint(0, len(links)-1)].attrs["href"]#隨機擷取一個來繼續爬20     print(newArticle)21     links = getLinks(newArticle)

運行結果(一分鐘150條資料產生,如非手動停止應該不會停止爬取)

 

 

 

 二 採集整個網站

 對整個網站進行所有鏈路採集,當然像wiki這些大型網站資料很多,要全部採集基本不可能。

 1 from urllib.request import urlopen 2 from bs4 import BeautifulSoup 3 import re 4 pages = set() 5 def getLinks(pageUrl): 6     global pages 7     html = urlopen("http://en.wikipedia.org"+pageUrl) 8     bsObj = BeautifulSoup(html,"lxml") 9     try:10         print(bsObj.h1.get_text())11         print(bsObj.find(id="mw-content-text").findAll("p")[0])12         print(bsObj.find(id="ca-edit").find("span").find("a").attrs[‘href‘])13     except AttributeError:14         print("頁面缺少一些屬性!不過不用擔心!")15     for link in bsObj.findAll("a", href=re.compile("^(/wiki/)")):16         if ‘href‘ in link.attrs:17             if link.attrs[‘href‘] not in pages:18                 # 我們遇到了新頁面19                 newPage = link.attrs[‘href‘]20                 print("----------------\n"+newPage)21                 pages.add(newPage)22                 getLinks(newPage)23 getLinks("")

運行結果

 

 遞迴爬取網頁原理:

 

 

 三 採用Scrapy採集

 高樓大廈都是從最簡單的一磚一瓦疊起來,寫網路爬蟲也是很多簡單的重複的操作組成,找到頁面的關鍵資訊和外鏈,然後再如此迴圈。而Scrapy庫,可以大幅度降低網頁連結尋找(不用自己去搞一大堆的過濾條件和Regex)還可以降低識別的工作複雜度。

使用參考;https://scrapy-chs.readthedocs.io/zh_CN/latest/intro/tutorial.html

 第一步 建立Scrapy項目

報錯,安裝scrapy,cmd-pip install scrapy

 

報錯,沒有安裝visual 14

重新安裝成功,再次執行 

scrapy startproject tutorial

建立成功後,目錄結構如下

第二步 定義資料來源,修改item(參考官網)

 

第三步 建立爬蟲class(參考官網)

 

 

 第四步 進入spider目錄,然後運行爬蟲

報錯,缺少win32庫

 

pip install pywin32

 

 再次運行成功

 

第一個Scrapy的helloworld基本完成,這個過程大致如下:

Scrapy為Spider的 start_urls 屬性中的每個URL建立了 scrapy.Request 對象,並將 parse 方法作為回呼函數(callback)賦值給了Request。

Request對象經過調度,執行產生 scrapy.http.Response 對象並送回給spider parse() 方法。

 

 如有用到,後面繼續深入學習Scrapy。

 

Python資料擷取-開始爬蟲

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.