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

时间:2018-07-12 07:23:36

标签: python go web-scraping beautifulsoup

FTR我已经在两个框架中成功编写了许多刮板,但是我很沮丧。这是我要抓取的数据的屏幕截图(您也可以转到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”仅出现在该表中):

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

}     }

1 个答案:

答案 0 :(得分:2)

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