【问题标题】:Cant find table with soup.findAll('table') using BeautifulSoup in python在python中使用BeautifulSoup找不到带有soup.findAll('table')的表
【发布时间】:2013-11-11 03:05:15
【问题描述】:

我正在使用 soup.findAll('table') 尝试在 html 文件中查找表格,但它不会出现。 该表确实存在于文件中,并且使用正则表达式我可以通过这种方式找到它:

import sys
import urllib2
from bs4 import BeautifulSoup
import re
webpage = open(r'd:\samplefile.html', 'r').read()
soup = BeautifulSoup(webpage)
print re.findall("TABLE",webpage)   #works, prints ['TABLE','TABLE']
print soup.findAll("TABLE")   # prints an empty list []

我知道从那时起我就正确地生成了汤:

print [tag.name for tag in soup.findAll(align=None)]

它将正确打印它找到的标签。我已经尝试过用不同的方式来写“表”,比如“表”、“表”等。 另外,如果我打开文件并用文本编辑器编辑它,它上面有“TABLE”。

为什么beautifulsoup 找不到表??

【问题讨论】:

  • 你能发一个这个html文件的样本吗?
  • 我也有同样的问题。试图从 ESPN.com 抓取。 ` url = 'scores.espn.go.com/nfl/boxscore?gameId=331010003' boxurl = urllib2.urlopen(url).read() soup = BeautifulSoup(boxurl) soupTables = soup.findAll('table') reTables = re.findall('table', boxurl) print len (soupTables), len(reTables) `soup.findAll 只返回 1 个表,而 re.findall 找到 46 个表
  • @user2333196 在将http:// 添加到网址后(这样我就可以实际下载它),len(soup.findAll('table')) 为我返回了 23。
  • @mr2ert 是的,你可以在这里找到它:jsbin.com/EjaqegU/3/watch?html,output
  • 我将您的 html 复制到我计算机上的本地文件中,并在 ipython 中运行您的代码,它工作正常,我得到 1 个表。你试过用最少的代码在 ipython 中运行它吗?

标签: python-2.7 beautifulsoup tags find findall


【解决方案1】:

上下文

  • python 2.x
  • BeautifulSoup HTML 解析器

问题

  • bsoup findall 不会返回所有预期的标签,或者根本不返回任何标签,即使用户知道标签中存在标签

解决方案

  • 尝试在初始化BeautifulSoup 构造函数时指定准确的解析器
## 前 汤= BeautifulSoup(网页) ## 后 汤= BeautifulSoup(网页,“html5lib”)

基本原理

  • 目标标记可能包含格式错误的 HTML,并且使用不同的解析器有不同程度的成功。

另见

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-19
    • 1970-01-01
    • 2013-11-17
    相关资源
    最近更新 更多