gpt4 book ai didi

python - 使用 BeautifulSoup 或 golang colly 解析 HTML 时遇到问题

转载 作者:IT王子 更新时间:2023-10-29 02:37:23 32 4
gpt4 key购买 nike

FTR 我已经在这两个框架中成功地编写了很多爬虫,但我被难住了。这是我试图抓取的数据的屏幕截图(您也可以转到获取请求中的实际链接):

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”只出现在该表中):

>>> "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

关于python - 使用 BeautifulSoup 或 golang colly 解析 HTML 时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51299572/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com