Last active
August 29, 2015 14:11
-
-
Save koduki/c1a4255326edfc1941b9 to your computer and use it in GitHub Desktop.
goqueryでHTMLの解析をする ref: http://qiita.com/koduki/items/393576193c25dbb477ed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$ go get github.com/PuerkitoBio/goquery |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"log" | |
"os" | |
"github.com/PuerkitoBio/goquery" | |
) | |
func ReplaceLinks() { | |
// ファイルからドキュメントを作成 | |
f, e := os.Open("./index.html") | |
if e != nil { | |
log.Fatal(e) | |
} | |
defer f.Close() | |
doc, e := goquery.NewDocumentFromReader(f) | |
if e != nil { | |
log.Fatal(e) | |
} | |
// DOMを解析してhrefの値を変更 | |
doc.Find(".list td a").Each(func(i int, s *goquery.Selection) { | |
s.SetAttr("href", fmt.Sprintf("%03d.html", i+1)) | |
}) | |
// 変更したDOMの値をHTMLとして標準出力 | |
result, e := doc.Html() | |
if e != nil { | |
log.Fatal(e) | |
} | |
fmt.Print(result) | |
} | |
func main() { | |
ReplaceLinks() | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment