登录
首页 >  Golang >  Go问答

在处理 HTML 时,使用BeautifulSoup或Golang Colly遇到了困难

来源:stackoverflow

时间:2024-03-11 23:18:25 311浏览 收藏

学习Golang要努力,但是不要急!今天的这篇文章《在处理 HTML 时,使用BeautifulSoup或Golang Colly遇到了困难》将会介绍到等等知识点,如果你想深入学习Golang,可以关注我!我会持续更新相关文章的,希望对大家都能有所帮助!

问题内容

ftr 我已经在这两个框架中成功编写了相当多的抓取工具,但我很困惑。这是我尝试抓取的数据的屏幕截图(您也可以转到获取请求中的实际链接):

我尝试定位 div.section_content

import requests
from bs4 import beautifulsoup
html = requests.get("https://www.baseball-reference.com/boxes/ari/ari201803300.shtml").text
soup = beautifulsoup(html)
soup.findall("div", {"class": "section_content"})

打印最后一行会显示其他一些 div,但不会显示包含投球数据的 div。

但是,我可以在文本中看到它,因此这不是 javascript 触发的加载问题(短语“pitching”仅出现在该表中):

>>> "pitching" in soup.text
true

这是 golang 尝试之一的缩写版本:

package main

import (
    "fmt"
    "github.com/gocolly/colly"
) 

func main() {
    c := colly.NewCollector(
            colly.AllowedDomains("www.baseball-reference.com"),
    )   
    c.OnHTML("div.table_wrapper", func(e *colly.HTMLElement) {
            fmt.Println(e.ChildText("div.section_content"))
    })  
    c.Visit("https://www.baseball-reference.com/boxes/ARI/ARI201803300.shtml")

} }


解决方案


在我看来,html 实际上被注释掉了,所以这就是 beautifulsoup 找不到它的原因。在解析 html 字符串之前删除注释标记,或者使用 beautifulsoup 到 extract the comments 并解析返回值。

例如:

for element in soup(text=lambda text: isinstance(text, Comment)):
    comment = element.extract()
    comment_soup = BeautifulSoup(comment)
    # work with comment_soup

好了,本文到此结束,带大家了解了《在处理 HTML 时,使用BeautifulSoup或Golang Colly遇到了困难》,希望本文对你有所帮助!关注golang学习网公众号,给大家分享更多Golang知识!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>