func parseColumnLabels(body string) ([]string, error) { tkn :=…
- User
func parseColumnLabels(body string) ([]string, error) { tkn := html.NewTokenizer(strings.NewReader(body))
codevar isTh bool var columnLabels []string for { tt := tkn.Next() switch { case tt == html.ErrorToken: if tkn.Err() == io.EOF { return columnLabels, nil } else { return nil, tkn.Err() } case tt == html.StartTagToken: t := tkn.Token() isTh = t.Data == "th" case tt == html.TextToken: t := tkn.Token() if isTh { _ = append(columnLabels, t.Data) } isTh = false case tt == html.EndTagToken: break } } return columnLabels, nil}
func ParseHtml(URL string) { body, err := getHtmlPage(URL) if err != nil { log.Fatalf("Could not get HTML page: %v", err) }
codecolumnLabels, err := parseColumnLabels(body) if err != nil { log.Fatalf("Could not parse column labels: %v", err) } for i := range columnLabels { fmt.Println(columnLabels[i]) }}
why does parsecolumnlabels return empty?
- Assistant
The issue likely lies in how the
appendfunction is being used in theparseColumnLabelsfunction. Specifically, the_ = append(columnLabels, t.Data)does not actually update thecolumnLabelsslice with the appended value.In Go, slices are references to arrays. When you append to a slice, if there's enough capacity in the underlying array, the slice is updated in-place. However, if there's not enough capacity, a new array is allocated, and the slice is updated to reference this new array. The
appendfunction returns the updated slice. Therefore, it is crucial to use the returned value of theappendfunction.To fix this issue, replace:
go_ = append(columnLabels, t.Data)with:
gocolumnLabels = append(columnLabels, t.Data)This change ensures that is updated each time a new label is appended, rather than discarding the result of the operation.
- User
can you make the code more efficient?
- Assistant