python - 使用Beautiful soup分析python中的表

标签 python html parsing beautifulsoup

所以我有一张 table :

<table border="1" style="width: 100%">
  <caption></caption>
  <col>
  <col>
  <tbody>
<tr>
  <td>Pig</td>
  <td>House Type</td>
</tr>
<tr>
  <td>Pig A</td>
  <td>Straw</td>
</tr>
<tr>
  <td>Pig B</td>
  <td>Stick</td>
</tr>
<tr>
  <td>Pig C</td>
  <td>Brick</td>
</tr>

我只是想返回一个表对的 JSON 字符串,如下所示:

[["Pig A", "Straw"], ["Pig B", "Stick"], ["Pig C", "Brick"]]

但是,使用我的代码,我似乎无法摆脱 HTML 标签:

stable = soup.find('table')

cells = [ ]
rows = stable.findAll('tr')
for tr in rows[1:4]:
    # Process the body of the table
    row = []
    td = tr.findAll('td')
    #td = [el.text for el in soup.tr.finall('td')]
    row.append( td[0])
    row.append( td[1])
    cells.append( row )


return cells

#最终,我想这样做: #h = json.dumps(单元格) #返回h

我的输出是这样的:

[[<td>Pig A</td>, <td>Straw</td>], [<td>Pig B</td>, <td>Stick</td>], [<td>Pig C</td>, <td>Brick</td>]]

最佳答案

使用 text 属性仅获取元素的内部文本:

row.append(td[0].text)
row.append(td[1].text)

关于python - 使用Beautiful soup分析python中的表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21591128/

相关文章:

python - 如何在 Win 和 MAC 上使用 Python 检测进程是否正在运行

html - CSS 下拉菜单

html - 有标准的 "smallest possible computer screen width"吗?

python - 具有不同环境的 iPython(使用 anaconda)

python - 无法从 QVBoxLayout 中删除边距

python - 我无法让我的类(class)在 pygame 中工作

html - IE9宽度问题

java - 在Java中解析C风格程序员的整数

performance - 从具有增强性能的文本文件中删除重复出现的行

Python3,通过单击按钮从url下载文件