如何提取<table>下的所有源代码并导出为html?

How to extract all the source code under <table> and export as html?

我是Scrapy的初学者。我的目标是 从大 HTML 页面中提取选定的表格,然后以 HTML 格式 将选定的表格一起导出。所以本质上,我想要的是 获得原始网页的较短版本,仅保留 <table> 部分 .

每个 <table> 部分的结构如下所示:

<table>
   <tbody>
      <tr>
        <td> 
          <font>

目前,我正在尝试以下蜘蛛代码,但问题是:

  1. 它不保留所有源格式;
  2. 不包括<table></table>
  3. 我不知道如何将抓取的结果保存为 html 格式。

  def parse(self, response):
      hxs = HtmlXPathSelector(response)
      titles = hxs.select("//document/type/sequence/filename/description/text/table")
      items = []
      for titles in titles:
          item = MyHtmlItem()
          item ["htmltext"] = titles.select("node()").extract()
          if (item["htmltext"]):
              items.append(item)
      return items

谁能给我一些建议?

如果我理解正确,你只需要从页面中提取原始表格html,那么解决方案很简单:

def parse(self, response):
    # XPath query to get all tables from response
    tables_selectors = response.xpath('//table')
    tables_html = tables_selectors.extract()
    ...

tables_html 是原始表 html 中的字符串数组。随意处理。

一些建议:

你的语法看起来有点过时,似乎你使用的是过时的 Scrapy 手册。

请在 official site

查看最新文档

使用表时,请注意 XPath 查询中的 tbody 标记。

希望对您有所帮助!