【问题标题】:BeautifulSoup is closing a the table after the first cellBeautifulSoup 在第一个单元格之后关闭表格
【发布时间】:2014-05-28 02:49:11
【问题描述】:

美好的一天,

我正在尝试使用 Python 2.7 / BeautifulSoup4 来解析一堆页面。其中一页是这一页:http://www.eliteprospects.com/player.php?player=3664

我的问题是我试图从主表中获取数据,但汤在第一个单元格之后关闭了表。

所以我的代码是这样的:

soup = BeautifulSoup(requests.get(url).text, "html.parser")
t = soup.findAll('table', 'tableborder')

t 的长度为 3,如果我使用 html5lib 或不定义解析器,则 t 为零。我无法将 lxml 安装在我的计算机上进行尝试。

所以主表,源代码中的t[0]是这样的:

<table cellpadding="0" cellspacing=0 width=100% class="tableborder" >
   <tr class="trbackground" height="20">
   <td align="left"><font color="white"><strong>&nbsp;Season</strong></font></a></td>
   <td align="left"><font color="white"><strong>Team</strong></font></td>
   <td align="left"><font color="white"><strong>League</strong></font></td>
   <td align="right"><font color="white"><strong>GP</strong></font></td>
   <td align="right"><font color="white"><strong>G</strong></font></td>
...

t[1] 和 t[2] 是不同的表,可以拉取整个表。但是 t[0] 看起来像这样:

<table cellpadding="0" cellspacing="0" class="tableborder" width="100%">
<tr class="trbackground" height="20">
<td align="left"><font color="white"><strong> Season</strong></font></td></tr></table>

似乎在第一个单元格之后结束了表格。我不确定它为什么这样做或如何阻止它。几个月前,同样的脚本在同一个页面上确实有效。他们可能已经更新了他们的源代码,但我不确定是什么导致了错误。

另外尝试使用不同的方法识别该表会产生相似的结果,例如:

t = soup.findAll('table', width='100%', cellspacing='0', cellpadding='0')

【问题讨论】:

    标签: python beautifulsoup


    【解决方案1】:

    你需要安装lxmllet BeautifulSoup use it

    >>> soup = BeautifulSoup(requests.get(url).text, "lxml")
    >>> t = soup.findAll('table', 'tableborder')
    >>> len(t)
    4
    >>> len(t[0].find_all('td'))
    527
    

    而且,为了说明区别,html.parser 发生了什么:

    >>> soup = BeautifulSoup(requests.get(url).text, "html.parser")
    >>> t = soup.findAll('table', 'tableborder')
    >>> len(t)
    4
    >>> len(t[0].find_all('td'))
    1
    

    【讨论】:

      猜你喜欢
      • 2018-06-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-29
      • 1970-01-01
      • 1970-01-01
      • 2017-09-07
      • 1970-01-01
      相关资源
      最近更新 更多