【问题标题】:BeautifulSoup, findAll('table') returns all tables but also the text between themBeautifulSoup, findAll('table') 返回所有表格以及它们之间的文本
【发布时间】:2017-02-19 03:58:01
【问题描述】:

我正在尝试隔离网页的一部分,不幸的是它没有包含在我可以提取的任何内容中。

我能得到的最接近的方法是获取网页的整个正文,然后尝试删除表格(这是我唯一不想要的部分)。

Example Page

我正在使用的代码:

storyText = soup.body
toRemove = storyText.findAll('table')
for each in toRemove:
    print each

目前的问题是 toRemove 行返回表格它们之间包含的文本,但不是 in 它们。

所以我得到:

<body>
<table>
    table stuff
</table>
    Text, not in tags </br> #This is what I want.
<table>
    table stuff
</table
</body>

我通过执行以下操作解决了我的问题:

# Isolate body
findBody = soup.body
new = str(findBody)
# Section off the text from the tables before it.
sec = new.split('</table>')
# Select story area
newStory = sec[3]
# Section off the text from the tables after it.
newSec = newStory.split('<table')
# Select the story area, this the area that we want.
story = newSec[0]

我仍在寻找答案,因为似乎应该有更清洁的方法来做到这一点。

【问题讨论】:

  • 鉴于您正在尝试获取所有文本,所以在示例页面上?
  • 从它开始,是的。

标签: python web-scraping beautifulsoup html-table


【解决方案1】:

您的代码在我的 Mac 上运行良好。 你用的是哪个版本?我用的是美汤 4。

(不推荐美汤3。因为,已经不再开发了。http://www.crummy.com/software/BeautifulSoup/bs4/doc/

这是我的代码:

from bs4 import BeautifulSoup

contents = '''<body>
<table>
     table stuff1
</table>
     Text, not in tags </br> #This is what I want.
<table>
     table stuff2
</table>
</body>'''

soup = BeautifulSoup(contents)

storyText = soup.body
toRemove = storyText.findAll('table')
for each in toRemove:
    print each
    each.extract()

print '----result-------------'
print soup

会出现以下结果。

<table>
    table stuff1
</table>
<table>
    table stuff2
</table>
----result-------------
<body>

    Text, not in tags  #This is what I want.

</body>

【讨论】:

  • 我正在使用 BS4,我尝试过使用适合您的代码,但它没有满足我的需求,它同时删除了表格 文本我想喝汤。
  • 嗯,这可能是由默认的 HTML 解析器引起的。将我的代码的第 13 行更改如下: `soup = BeautifulSoup(contents, 'html5lib') ` 您可以使用以下命令之一安装 html5lib: $ apt-get install python-html5lib $ easy_install html5lib $ pip install html5lib
猜你喜欢
  • 2019-02-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-21
  • 1970-01-01
  • 2017-01-21
  • 2021-10-07
  • 1970-01-01
相关资源
最近更新 更多