第一步
首先我們必須安裝Go,下載和安裝Go的說明。
我們為專案建立一個新資料夾,移動到該目錄並執行以下命令:
go mod init scraper
? go mod init 指令用於在運行目錄中初始化一個新的 Go 模組,並建立一個 go.mod 檔案來追蹤程式碼依賴關係。依賴管理
現在讓我們安裝 Colibri:
go get github.com/gonzxlez/colibri
? Colibri 是一個 Go 包,它允許我們使用 JSON 中定義的一組規則來抓取和提取網路上的結構化資料。儲存庫
提取規則
我們定義了 colibri 用於提取我們需要的資料的規則。文件
我們將向 URL https://pkg.go.dev/search?q=xpath 發出 HTTP 請求,其中包含與 Go Packages 中 xpath 相關的 Go 套件的查詢結果。
使用網頁瀏覽器中包含的開發工具,我們可以檢查頁面的 HTML 結構。瀏覽器開發工具有哪些?
<div class="SearchSnippet"> <div class="SearchSnippet-headerContainer"> <h2> <a href="/github.com/antchfx/xpath" data-gtmc="search result" data-gtmv="0" data-test-id="snippet-title"> xpath <span class="SearchSnippet-header-path">(github.com/antchfx/xpath)</span> </a> </h2> </div> <div class="SearchSnippet-infoLabel"> <a href="/github.com/antchfx/xpath?tab=importedby" aria-label="Go to Imported By"> <span class="go-textSubtle">Imported by </span><strong>143</strong> </a> <span class="go-textSubtle">|</span> <span class="go-textSubtle"> <strong>v1.2.5</strong> published on <span data-test-id="snippet-published"><strong>Oct 26, 2023</strong></span> </span> <span class="go-textSubtle">|</span> <span data-test-id="snippet-license"> <a href="/github.com/antchfx/xpath?tab=licenses" aria-label="Go to Licenses"> MIT </a> </span> </div> </div>
表示查詢結果的 HTML 結構片段。
然後我們需要一個選擇器「packages」,它將在HTML 中尋找類別SearchSnippet 類別的所有div 元素,從這些元素中選擇一個選擇器「 name」 將採用元素h2 內元素a 的文字和選擇器「path” 將採用 中a 元素的href 元素的href > 元素。換句話說,「名稱」
將採用Go包的名稱,「
{ "method": "GET", "url": "https://pkg.go.dev/search?q=xpath", "timeout": 10000, "selectors": { "packages": { "expr": "div.SearchSnippet", "all": true, "type": "css", "selectors": { "name": "//h2/a/text()", "path": "//h2/a/@href" } } } }將採用包的路徑:)
- method: 指定 HTTP 方法(GET、POST、PUT...)。
- url: 請求的 URL。
- 逾時: HTTP 請求的逾時(以毫秒為單位)。
- 選擇器:選擇器。
「packages」
- : 是選擇器的名稱。
- expr: 選擇器表達式。
- all: 指定所有應找到與表達式相符的元素。
- type: 表達式的類型,在本例中為 CSS 選擇器。
- 選擇器:巢狀選擇器。 “name” 和
是選擇器的名稱,它們的值是表達式,在本例中是 XPath 表達式。
- 選擇器:選擇器。
「packages」
Go 中的程式碼
package main import ( "encoding/json" "fmt" "github.com/gonzxlez/colibri" "github.com/gonzxlez/colibri/webextractor" ) var rawRules = `{ "method": "GET", "url": "https://pkg.go.dev/search?q=xpath", "timeout": 10000, "selectors": { "packages": { "expr": "div.SearchSnippet", "all": true, "type": "css", "selectors": { "name": "//h2/a/text()", "path": "//h2/a/@href" } } } }` func main() { we, err := webextractor.New() if err != nil { panic(err) } var rules colibri.Rules err = json.Unmarshal([]byte(rawRules), &rules) if err != nil { panic(err) } output, err := we.Extract(&rules) if err != nil { panic(err) } fmt.Println("URL:", output.Response.URL()) fmt.Println("Status code:", output.Response.StatusCode()) fmt.Println("Content-Type", output.Response.Header().Get("Content-Type")) fmt.Println("Data:", output.Data) }我們準備建立 scraper.go 文件,導入必要的套件並定義主函數:
? WebExtractor 是 Colibri 的預設接口,可以開始在網路上抓取或提取資料。
使用 webextractor 的新功能,我們產生一個 Colibri 結構,其中包含開始提取資料所需的內容。
然後我們將 JSON 格式的規則轉換為 Rules 結構,並呼叫 Extract 方法將規則作為參數傳送。
我們獲得輸出,HTTP 回應的 URL、HTTP 狀態代碼、回應的內容類型以及使用選擇器提取的資料都列印在螢幕上。請參閱輸出結構的文件。
go mod tidy我們執行以下指令:
? go mod tidy 指令確保 go.mod 中的依賴項與模組原始碼相符。
go run scraper.go最後,我們使用以下命令在 Go 中編譯並執行程式碼:
結論
在這篇文章中,我們學習如何使用 Colibri 套件在 Go 中執行網頁抓取,使用 CSS 和 XPath 選擇器定義擷取規則。 Colibri 是為那些希望在 Go 中自動化 Web 資料收集的人提供的工具。其基於規則的方法和易用性使其成為所有經驗水平的開發人員的一個有吸引力的選擇。 簡而言之,Go 中的網頁抓取是一種強大且多功能的技術,可用於從各種網站中提取資訊。需要強調的是,網頁抓取必須符合道德規範,尊重網站的條款和條件,並避免伺服器超載。
以上是網頁抓取的詳細內容。更多資訊請關注PHP中文網其他相關文章!

Gohandlesinterfacesandtypeassertionseffectively,enhancingcodeflexibilityandrobustness.1)Typeassertionsallowruntimetypechecking,asseenwiththeShapeinterfaceandCircletype.2)Typeswitcheshandlemultipletypesefficiently,usefulforvariousshapesimplementingthe

Go語言的錯誤處理通過errors.Is和errors.As函數變得更加靈活和可讀。 1.errors.Is用於檢查錯誤是否與指定錯誤相同,適用於錯誤鏈的處理。 2.errors.As不僅能檢查錯誤類型,還能將錯誤轉換為具體類型,方便提取錯誤信息。使用這些函數可以簡化錯誤處理邏輯,但需注意錯誤鏈的正確傳遞和避免過度依賴以防代碼複雜化。

tomakegoapplicationsRunfasterandMorefly,useProflingTools,leverageConCurrency,andManageMoryfectily.1)usepprofforcpuorforcpuandmemoryproflingtoidentifybottlenecks.2)upitizegorizegoroutizegoroutinesandchannelstoparalletaparelalyizetasksandimproverperformance.3)

go'sfutureisbrightwithtrendslikeMprikeMprikeTooling,仿製藥,雲 - 納蒂維德象,performanceEnhancements,andwebassemblyIntegration,butchallengeSinclainSinClainSinClainSiNgeNingsImpliCityInsImplicityAndimimprovingingRornhandRornrorlling。

goroutinesarefunctionsormethodsthatruncurranceingo,啟用效率和燈威量。 1)shememanagedbodo'sruntimemultimusingmultiplexing,允許千sstorunonfewerosthreads.2)goroutinessimproverentimensImproutinesImproutinesImproveranceThroutinesImproveranceThrountinesimproveranceThroundinesImproveranceThroughEasySytaskParallowalizationAndeff

purposeoftheInitfunctionoIsistoInitializeVariables,setUpConfigurations,orperformneccesSetarySetupBeforEtheMainFunctionExeCutes.useInitby.UseInitby:1)placingitinyourcodetorunautoamenationally oneraty oneraty oneraty on inity in ofideShortAndAndAndAndForemain,2)keepitiTshortAntAndFocusedonSimImimpletasks,3)

Gointerfacesaremethodsignaturesetsthattypesmustimplement,enablingpolymorphismwithoutinheritanceforcleaner,modularcode.Theyareimplicitlysatisfied,usefulforflexibleAPIsanddecoupling,butrequirecarefulusetoavoidruntimeerrorsandmaintaintypesafety.

在Go中使用recover()函數可以從panic中恢復。具體方法是:1)在defer函數中使用recover()捕獲panic,避免程序崩潰;2)記錄詳細的錯誤信息以便調試;3)根據具體情況決定是否恢復程序執行;4)謹慎使用,以免影響性能。


熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

Dreamweaver CS6
視覺化網頁開發工具

mPDF
mPDF是一個PHP庫,可以從UTF-8編碼的HTML產生PDF檔案。原作者Ian Back編寫mPDF以從他的網站上「即時」輸出PDF文件,並處理不同的語言。與原始腳本如HTML2FPDF相比,它的速度較慢,並且在使用Unicode字體時產生的檔案較大,但支援CSS樣式等,並進行了大量增強。支援幾乎所有語言,包括RTL(阿拉伯語和希伯來語)和CJK(中日韓)。支援嵌套的區塊級元素(如P、DIV),

記事本++7.3.1
好用且免費的程式碼編輯器

SAP NetWeaver Server Adapter for Eclipse
將Eclipse與SAP NetWeaver應用伺服器整合。

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)