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 算法使用了tf-idf,用手肘图确定k值确定不了,第四轮廓系数又太小才有0.006088746097507285,如何解决?(相关搜索:数据处理)
  • ¥15 彩灯控制电路,会的加我QQ1482956179
  • ¥200 相机拍直接转存到电脑上 立拍立穿无线局域网传
  • ¥15 (关键词-电路设计)
  • ¥15 如何解决MIPS计算是否溢出
  • ¥15 vue中我代理了iframe,iframe却走的是路由,没有显示该显示的网站,这个该如何处理
  • ¥15 操作系统相关算法中while();的含义
  • ¥15 CNVcaller安装后无法找到文件
  • ¥15 visual studio2022中文乱码无法解决