有没有可能BeautifulSoup不能解析html文档中的表?

2024-06-17 07:48:31 发布

您现在位置:Python中文网/ 问答频道 /正文

下面是我用来刮表的代码示例:

with open ('text.txt', 'w') as algroo:
    for row in RoOtbody.find_all('tr'):
        for cell in row.find_all('td'):
            algroo.write(cell.text)
        algroo.write('\n')

我已经使用Selenium和requests从网页中提取外部html。我也试着用html.parser语法分析器和lxml。你知道吗

html如下所示:

<tr class="table">
                     <td class="table" valign="top">
                        <p class="tbl-hdr">HS heading</p>
                     </td>
                     <td class="table" valign="top">
                        <p class="tbl-hdr">Desccription of product</p>
                     </td>
                     <td class="table" colspan="2" valign="top">
                        <p class="tbl-hdr">Working or processing, carried out on non-originating
materials, which confers originating status</p>
                     </td>
                  </tr>

问题是,当我打开txt文件时,所有单元格元素都在一个单独的列中,如下所示,literaly:

HS标题

产品描述

在非原产材料上进行的具有原产地位的加工或加工

在我观看和阅读的所有教程中,它们应该位于同一行,如下所示:

HS标题产品加工或加工的描述,在非原产材料上进行,授予原产地位

有人能帮我吗?你知道吗


Tags: texttxtforhdrtophtmltabletr
1条回答
网友
1楼 · 发布于 2024-06-17 07:48:31

我不知道这是否对你有帮助

from simplified_scrapy.simplified_doc import SimplifiedDoc 
html = '''<tr class="table">
                     <td class="table" valign="top">
                        <p class="tbl-hdr">HS heading</p>
                     </td>
                     <td class="table" valign="top">
                        <p class="tbl-hdr">Desccription of product</p>
                     </td>
                     <td class="table" colspan="2" valign="top">
                        <p class="tbl-hdr">Working or processing, carried out on non-originating
materials, which confers originating status</p>
                     </td>
                  </tr>'''
doc = SimplifiedDoc(html)
tr = doc.tr # get first tr
print (tr.text)
print (tr.getText(' '))
tds = tr.tds # get all td
for td in tds:
  print (td.text)

相关问题 更多 >