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
Joanna Shevchuk
September 22, 2019
Programming
0
380
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
Tweet
Share
More Decks by Joanna Shevchuk
See All by Joanna Shevchuk
pip uninstall depression
djeanne
0
86
Go for Python speakers
djeanne
0
89
Other Decks in Programming
See All in Programming
今から始めるClaude Code入門〜AIコーディングエージェントの歴史と導入〜
nokomoro3
0
180
Navigation 2 を 3 に移行する(予定)ためにやったこと
yokomii
0
270
go test -json そして testing.T.Attr / Kyoto.go #63
utgwkk
3
300
Navigating Dependency Injection with Metro
zacsweers
3
960
Swift Updates - Learn Languages 2025
koher
2
480
@Environment(\.keyPath)那么好我不允许你们不知道! / atEnvironment keyPath is so good and you should know it!
lovee
0
120
プロポーザル駆動学習 / Proposal-Driven Learning
mackey0225
2
1.3k
旅行プランAIエージェント開発の裏側
ippo012
2
910
さようなら Date。 ようこそTemporal! 3年間先行利用して得られた知見の共有
8beeeaaat
3
1.4k
HTMLの品質ってなんだっけ? “HTMLクライテリア”の設計と実践
unachang113
4
2.9k
Putting The Genie in the Bottle - A Crash Course on running LLMs on Android
iurysza
0
140
Android端末で実現するオンデバイスLLM 2025
masayukisuda
1
150
Featured
See All Featured
Building a Scalable Design System with Sketch
lauravandoore
462
33k
KATA
mclloyd
32
14k
CoffeeScript is Beautiful & I Never Want to Write Plain JavaScript Again
sstephenson
162
15k
GraphQLの誤解/rethinking-graphql
sonatard
72
11k
Practical Tips for Bootstrapping Information Extraction Pipelines
honnibal
PRO
23
1.4k
Put a Button on it: Removing Barriers to Going Fast.
kastner
60
4k
Java REST API Framework Comparison - PWX 2021
mraible
33
8.8k
[Rails World 2023 - Day 1 Closing Keynote] - The Magic of Rails
eileencodes
36
2.5k
RailsConf 2023
tenderlove
30
1.2k
Facilitating Awesome Meetings
lara
55
6.5k
Easily Structure & Communicate Ideas using Wireframe
afnizarnur
194
16k
10 Git Anti Patterns You Should be Aware of
lemiorhan
PRO
656
61k
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