package htmlparse import ( "fmt" "golang.org/x/net/html" "io" "log" "net/http" "strings"…
- User
package htmlparse
import ( "fmt" "golang.org/x/net/html" "io" "log" "net/http" "strings" )
var allEntries []classEntry
type classEntry struct { Name string PeriodEntries [][]string }
func getHtmlContents(URL string) (string, error) { resp, err := http.Get(URL) if err != nil { return "", err }
codedefer func(Body io.ReadCloser) { err = Body.Close() if err != nil { return } }(resp.Body) body, err := io.ReadAll(resp.Body) if err != nil { return "", err } return string(body), nil}
func getText(n *html.Node) string { if n.Type == html.TextNode { return n.Data } var text string for c := n.FirstChild; c != nil; c = c.NextSibling { text += getText(c) } return strings.TrimSpace(text) }
func getAttribute(n *html.Node, attrKey string) string { for _, a := range n.Attr { if a.Key == attrKey { return a.Val } } return "" }
func processRow(trNode *html.Node) { periodNum := 0 for cell := trNode.FirstChild; cell != nil; cell = cell.NextSibling { if cell.Type == html.ElementNode && cell.Data == "td" { colspan := getAttribute(cell, "colspan") if colspan == "8" { // Special handling for headers with colspan=8 // fmt.Println("Header with colspan=8:", getText(cell)) allEntries = append(allEntries, classEntry{Name: getText(cell)}) rowNum += 1 periodNum = 0 } else { // Process individual data entries allEntries[rowNum].PeriodEntries[periodNum][] = append(allEntries[rowNum].PeriodEntries[], getText(cell)) periodNum += 1 //fmt.Println("Data Entry:", getText(cell)) } } } }
var rowNum int
func parseClassEntries(htmlContent string) ([][]string, error) { rowNum = -1 doc, err := html.Parse(strings.NewReader(htmlContent)) if err != nil { panic("could not parse HTML") }
codetableCount := 0 var f func(*html.Node) f = func(n *html.Node) { if n.Type == html.ElementNode && n.Data == "table" { tableCount++ } if tableCount > 1 { if n.Type == html.ElementNode && n.Data == "tr" { processRow(n) } } for c := n.FirstChild; c != nil; c = c.NextSibling { f(c) } } f(doc) return nil, nil}
func ParseHtml(URL string) { body, err := getHtmlContents(URL) if err != nil { log.Fatalf("Could not get HTML page: %v", err) } log.Printf("Successfully downloaded HTML contents")
code - Assistant
The error you're encountering is due to a syntax mistake on this line: