【问题标题】:BeautifulSoup4 cannot locate table no matter what I try无论我尝试什么,BeautifulSoup4 都无法找到表
【发布时间】:2019-06-20 08:14:38
【问题描述】:

我正在尝试同时从网页中抓取 2 个表格。 BeautifulSoup 找到第一个表没有问题,但无论我尝试什么都找不到第二个表,这是网页:Hockey Reference: Justin Abdelkader

这是季后赛标题下方的表格。

这是我的代码。

        sauce = urllib.request.urlopen('https://www.hockey-reference.com/players/a/abdelju01/gamelog/2014', timeout=None).read()
        soup = bs.BeautifulSoup(sauce, 'html5lib')
        table = soup.find_all('table')
        print(len(table))

总是打印 1。

如果我打印(汤),并在终端中使用搜索功能,我可以找到 2 个单独的表格标签。我没有看到任何会阻碍 BS4 查找标签的 javascript。我也尝试通过 id 和 class 查找表,即使表的父 div 似乎也无法找到。有谁知道我做错了什么?

【问题讨论】:

标签: python pandas beautifulsoup


【解决方案1】:

由于 javascript 加载附加信息

今天requests_html 可以加载 html 页面也可以加载 javascript 内容。

pip install requests-html

from requests_html import HTMLSession
session = HTMLSession()
r = session.get('https://www.hockey-reference.com/players/a/abdelju01/gamelog/2014')
r.html.render()
res = r.html.find('table')
print(len(res))
4

【讨论】:

    【解决方案2】:

    第二个表格似乎在 HTML 注释标记 <--... <table class=... 内。我想这就是 BeautifulSoup 找不到它的原因。

    【讨论】:

      【解决方案3】:

      看起来那个表格是一个小部件——点击“分享和更多”->“嵌入这个表格”,你会得到一个带有链接的脚本:

      https://widgets.sports-reference.com/wg.fcgi?css=1&site=hr&url=%2Fplayers%2Fa%2Fabdelju01%2Fgamelog%2F2014&div=div_gamelog_playoffs

      我们如何解析它?

      import requests
      import bs4
      url = 'https://widgets.sports-reference.com/wg.fcgi?css=1&site=hr&url=%2Fplayers%2Fa%2Fabdelju01%2Fgamelog%2F2014&div=div_gamelog_playoffs'
      widget = requests.get(url).text
      fixed = '\n'.join(s.lstrip("document.write('").rstrip("');") for s in widget.splitlines())
      
      soup = bs4.BeautifulSoup(fixed)
      soup.find('td', {'data-stat': "date_game"}).text # => '2014-04-18'
      

      瞧!

      【讨论】:

        【解决方案4】:

        您可以使用 bs4 评论到达评论行,例如:

        from bs4 import BeautifulSoup , Comment
        from urllib import urlopen
        
        
        search_url = 'https://www.hockey-reference.com/players/a/abdelju01/gamelog/2014'
        
        page = urlopen(search_url)
        soup = BeautifulSoup(page, "html.parser")
        
        table = soup.findAll('table') ## html part with no comment
        table_with_comment = soup.findAll(text=lambda text:isinstance(text, Comment))
        [comment.extract() for comment in table_with_comment]
        ## print table_with_comment  print all comment line
        
        start = '<table class'
        
        for c in range(0,len(table_with_comment)):
            if start in table_with_comment[c]:
                 print table_with_comment[c] ## print comment line has <table class 
        

        【讨论】:

          猜你喜欢
          • 2020-08-11
          • 2021-07-29
          • 1970-01-01
          • 1970-01-01
          • 2020-10-31
          • 1970-01-01
          • 2020-10-01
          • 1970-01-01
          • 2011-06-30
          相关资源
          最近更新 更多