用beauthulsoup或golang colly解析HTML时出现问题

2024-09-27 00:23:09 发布

您现在位置:Python中文网/ 问答频道 /正文

FTR我在这两个框架中都成功地编写了不少scraper,但是我被难住了。下面是我试图获取的数据截图(您也可以转到get请求中的实际链接):

enter image description here

我试图瞄准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”只出现在该表中):

^{pr2}$

以下是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")

} }在


Tags: 数据httpsimportdivcomgethtmlwww
1条回答
网友
1楼 · 发布于 2024-09-27 00:23:09

在我看来,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

相关问题 更多 >

    热门问题