Upgrade to Pro
— share decks privately, control downloads, hide ads and more …
Speaker Deck
Features
Speaker Deck
PRO
Sign in
Sign up for free
Search
Search
Colly: a review of a web-scraping framework in Go
Search
Sponsored
·
Ship Features Fearlessly
Turn features on and off without deploys. Used by thousands of Ruby developers.
→
Joanna Shevchuk
September 22, 2019
Programming
380
0
Share
Colly: a review of a web-scraping framework in Go
A brief review of the web-scraping framework Colly, the most popular one among Gophers.
Joanna Shevchuk
September 22, 2019
More Decks by Joanna Shevchuk
See All by Joanna Shevchuk
pip uninstall depression
djeanne
0
91
Go for Python speakers
djeanne
0
93
Other Decks in Programming
See All in Programming
今さら聞けないCancellationToken
htkym
0
220
AIとASP.NET Coreで雑Webアプリを作った話
mayuki
0
190
These Five Tricks Can Make Your Apps Greener, Cheaper, & Nicer
hollycummins
0
270
TSKaigi 2026 TypeScriptバックエンドのオブザーバビリティ戦略 — Datadog × NestJSの実践
taiseiyamamotoan
2
270
inferと仲良くなる10分間
ryokatsuse
1
360
代数的データ型って何が嬉しいの? #frontend_phpcon_do
kajitack
8
3.1k
AI時代のUIはどこへ行く?その2!
yusukebe
19
6.5k
さぁV100、メモリをお食べ・・・
nilpe
0
130
脅威をエンジニアリングの糧にして――現場編 / Turning Threats into Engineering Fuel — Field Edition
nrslib
0
240
次世代リンターで探る、tsgo 時代における型認識カスタムルールの現実解
ytakahashii
3
1.4k
タクシーアプリ『GO』の バックエンド開発のおける AI利活用と若者のすべて
pyama86
3
1.8k
エージェンティックRAGにAWSで入門しよう!
har1101
5
120
Featured
See All Featured
From π to Pie charts
rasagy
0
200
Navigating Algorithm Shifts & AI Overviews - #SMXNext
aleyda
1
1.3k
4 Signs Your Business is Dying
shpigford
187
22k
Improving Core Web Vitals using Speculation Rules API
sergeychernyshev
21
1.5k
[SF Ruby Conf 2025] Rails X
palkan
2
1.1k
Unsuck your backbone
ammeep
672
58k
The Psychology of Web Performance [Beyond Tellerrand 2023]
tammyeverts
49
3.5k
The Illustrated Guide to Node.js - THAT Conference 2024
reverentgeek
1
370
The Invisible Side of Design
smashingmag
302
52k
VelocityConf: Rendering Performance Case Studies
addyosmani
333
25k
Ethics towards AI in product and experience design
skipperchong
2
300
Beyond borders and beyond the search box: How to win the global "messy middle" with AI-driven SEO
davidcarrasco
3
150
Transcript
Colly: обзор фреймворка для веб-скрейпинга на Go Joanna Shevchuk
О себе • Go + Python + Linux; • Менторю
Django Girls и курс PyLadies 1/22
Веб-скрейпинг извлечение данных из веб-страниц для последующей структуризации. 2/22
API Программный интерфейс приложения описание способов, помогающих одной программе взаимодействовать
с другой. Есть API - используем API. Нет API - используем скрейпер. 3/22
robots.txt наш_сайт/robots.txt User-agent: * Disallow: / (скрейпить нельзя помиловать **)
4/22
Colly: Fast and Elegant Scraping Framework for Gophers 5/22
Преимущества • Толковый API и подробная документация; • Много плюшек;
• На Go = привычнее; • Конкурентность. 6/22
О плюшках: • Скрейпит синхронно/асинхронно/параллельно; • Автоматически кодирует не-Юникодные символы;
• Сам вычищает cookies; • Обрабатывает robots.txt; • Можно прикрутить БД: SQLite или MongoDB; 7/22
Недостатки • Нет встроенного headless-браузера; Headless browser браузер без графического
интерфейса (работает через командную строку). 8/22
func main() { c := colly.NewCollector() c.OnHTML("a[href]", func(e *colly.HTMLElement) {
e.Request.Visit(e.Attr("href")) }) c.OnRequest(func(r *colly.Request) { fmt.Println("Visiting", r.URL) }) c.Visit("http://go-colly.org/") } 9/22
type Collector struct { UserAgent string MaxDepth int AllowedDomains []string
DisallowedDomains []string DisallowedURLFilters []*regexp.Regexp URLFilters []*regexp.Regexp AllowURLRevisit bool MaxBodySize int CacheDir string IgnoreRobotsTxt bool Async bool ParseHTTPErrorResponse bool ID uint32 DetectCharset bool RedirectHandler func(req *http.Request, via []*http.Request) error CheckHead bool } 10/22
User Agent как концепция приложение, через определенный сетевой протокол обеспечивающее
доступ к веб-контенту (например, браузер или скрейпер). как элемент строка, содержащая сведения о браузере или скрейпере: название, версия, платформа (ОС), движок. 11/22
Скрейпим статический сайт package main import ( "encoding/csv" "log" "os"
"github.com/gocolly/colly" ) func main() { fName := "xkcd_store_items.csv" file, err := os.Create(fName) if err != nil { log.Fatalf("Cannot create file %q: %s\n", fName, err) return } 12/22
... defer file.Close() writer := csv.NewWriter(file) defer writer.Flush() writer.Write([]string{"Name", "Price",
"URL", "Image URL"}) c := colly.NewCollector( colly.AllowedDomains("store.xkcd.com"), ) ... 13/22
... c.OnHTML(‘.next a[href]‘, func(e *colly.HTMLElement) { e.Request.Visit(e.Attr("href")) }) c.Visit("https://store.xkcd.com/collections/everything") log.Printf("Scraping
finished, check file %q for results\n", fName) log.Println(c) } 14/22
Скрейпим динамический сайт (не через родной API) Instagram Под капотом
есть goquery. • Исходный код страницы • Ищем переменную window._sharedData 15/22
c := colly.NewCollector() c.OnHTML("body > script:first-of-type", func(e *colly.HTMLElement ) {
jsonData := e.Text[strings.Index(e.Text, "{") : len(e.Text) -1] 16/22
data := struct { EntryData struct { ProfilePage []struct {
User struct { Id string ‘json:"id"‘ Media struct { Nodes []struct { ImageURL string ‘json:"display_src "‘ ThumbnailURL string ‘json:" thumbnail_src"‘ IsVideo bool ‘json:"is_video"‘ Date int ‘json:"date"‘ Dimensions struct { Width int ‘json:"width"‘ Height int ‘json:"height"‘ } } ... 17/22
... PageInfo pageInfo ‘json:"page_info"‘ } ‘json:"media"‘ } ‘json:"user"‘ } ‘json:"ProfilePage"‘
} ‘json:"entry_data"‘ }{} err := json.Unmarshal([]byte(jsonData), &data) if err != nil { log.Fatal(err) } 18/22
page := data.EntryData.ProfilePage[0] actualUserId = page.User.Id for _, obj :=
range page.User.Media.Nodes { if obj.IsVideo { continue } c.Visit(obj.ImageURL) } } 19/22
const nextPageURLTemplate string = ‘https://www.instagram.com/ graphql/query/?query_id=17888483320059182&variables={"id":"%s ","first":12,"after":"%s"}‘ //... c.OnResponse(func(r *colly.Response)
{ if strings.Index(r.Headers.Get("Content-Type"), "image") > -1 { r.Save(outputDir + r.FileName()) return } } 20/22
http://go-colly.org/ https://github.com/gocolly/colly https://godoc.org/github.com/gocolly/colly https://godoc.org/github.com/gocolly/colly/extensions 21/22
Мои контакты djeanne joannashevchuk ƻ djeanne djeanne.github.io
[email protected]
[email protected]
22/22