go - 使用 Go 抓取 HTML 下拉列表?

标签 go web-scraping

我正在使用程序包 golang.org/x/net/html 从 HTML 页面中抓取数据,到目前为止一切正常。但是,我不知道如何从这样的下拉列表中提取数据:

<!DOCTYPE html>
<html>
<body>

<select name="car" size="1" id="car">
  <option value="volvo">Volvo</option>
  <option value="saab">Saab</option>
  <option value="vw">VW</option>
  <option value="audi" selected>Audi</option>
</select>

<select name="animal" size="1" id="animal">
  <option value="dog">Dog</option>
  <option value="cat" selected>Cat</option>
  <option value="badger">Badger</option>
  <option value="mouse">Mouse</option>
</select>

我想提取预选的选项,所以结果变成这样:

car = audi
animal = cat

我怎样才能做到这一点?如果 golang.org/x/net/html 不能做我想做的事,我还能做些什么来提取数据?

最佳答案

你绝对可以用“net/html”做到这一点:

package main

import (
    "fmt"
    "golang.org/x/net/html"
    "strings"
)

func main() {
    s := "html"

    result := make(map[string]string)
    d := html.NewTokenizer(strings.NewReader(s))
    currID := ""
    for {
        tokenType := d.Next()
        if tokenType == html.ErrorToken {
            break
        }

        token := d.Token()
        switch tokenType {
        case html.StartTagToken:
            if token.Data == "select" {
                for _, a := range token.Attr {
                    if a.Key == "id" {
                        currID = a.Val
                    }
                }
            }
            if token.Data == "option" {
                isSelected := false
                for _, a := range token.Attr {
                    if a.Key == "selected" {
                        isSelected = true
                    }
                }
                if isSelected {
                    for _, a := range token.Attr {
                        if a.Key == "value" {
                            result[currID] = a.Val
                        }
                    }
                }
            }
        }
    }

    fmt.Printf("%v\n", result)
}

附言此代码可以改进。

关于go - 使用 Go 抓取 HTML 下拉列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43030443/

相关文章:

go - 在 goroutines 中启动 goroutines 是否可以接受?

web-scraping - 将 url 传递到从 RabbitMQ 使用的 scrapy 中的解析方法

excel - 在excel VBA中通过 Selenium 为每个谷歌搜索创建新标签

web-scraping - Puppeteer/Node - Target.createTarget - 目标关闭

go - 如何从特定路径打开goland?

go - MapScan 无法解码为非指针 int64

google-app-engine - 将结构 slice 转换为空接口(interface) slice

mongodb - Golang MongoDB 按字母顺序排序,跳过和限制

python - 使用 Requests 和 Beautifulsoup 在 Python 中抓取 PDF 文件

python - 使用selenium(python)抓取网页