dsg41888 2016-10-09 19:34
浏览 78
已采纳

如何在Golang中访问内部标签令牌?

I am making a webscraper and i have never done it before so please point out if i am doing anything wrong

I am using golang to scrap

suppose i have been given a table

<table>
   <tr>
         <td>XYZ</td>
         <td>XYZ</td>
         <td>XYZ</td> 
   </tr>
   <tr>
         <td>XYZ</td>
         <td>XYZ</td>
         <td>XYZ</td> 
   </tr>
   <tr>
         <td>XYZ</td>
         <td>XYZ</td>
         <td>XYZ</td> 
   </tr>
   <tr>
         <td>XYZ</td>
         <td>XYZ</td>
         <td>XYZ</td> 
   </tr>
</table>

i want to extract data from each tr but only the second td

also can i return a new html string only having the content inside the table tag and remove everything elese in the html outside table tag?

  • 写回答

2条回答 默认 最新

  • doumo6356 2016-10-09 21:11
    关注

    Well first of all your HTML example is wrong, you missed all the close tags </ tr > and </ td >

    For this kind of job is always better use some sort of DOM selectors like jQuery. For Go I recommend goquery, it's little library and works pretty well. Your solution:

    package main
    
    import (
        "log"
    
        "github.com/PuerkitoBio/goquery"
    )
    
    func main() {
        doc, err := goquery.NewDocument("http://your.url.com/foo.html")
        if err != nil {
            log.Fatal(err)
        }
    
        doc.Find("table tr").Each(func(_ int, tr *goquery.Selection) {
    
            // for each <tr> found, find the <td>s inside
            // ix is the index
            tr.Find("td").Each(func(ix int, td *goquery.Selection) {
    
                // print only the td number 2 (index == 1)
                if ix == 1 {
                    log.Printf("index: %d content: '%s'", ix, td.Text())
                }
            })
        })
    }
    

    As you may note td.Text() has the content of each td tag. I left you the full file that I used for testing https://play.golang.org/p/Rtb1Tqz1Wb

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制