【问题标题】:How can I assign a value to a null node in Xpath?如何将值分配给 Xpath 中的空节点?
【发布时间】:2015-04-28 22:42:51
【问题描述】:

这是我需要通过 Xpath 使用 scrapy 来抓取的部分:

<tr class="o"><td>Alabama</td><td><code>US.AL</code></td><td><code>US01</code></td><td>Ala.</td><td>-6~</td><td class="n">4,779,736</td><td class="n">133,916</td><td class="n">51,705</td><td>2</td><td>Montgomery</td><td>Alabamian</td><td>350-369</td></tr>
<tr class="e"><td>Alaska</td><td><code>US.AK</code></td><td><code>US02</code></td><td></td><td>-9~</td><td class="n">710,231</td><td class="n">1,530,700</td><td class="n">591,007</td><td>6</td><td>Juneau</td><td>Alaskan</td><td>995-999</td></tr>

我的 xpath 表达式是:

response.xpath('//tr[@class="o" or @class="e"][2]/descendant::*').extract()

但是“阿拉斯加”中有一个空节点。那是&lt;code&gt;“US02”之后的&lt;td&gt; 节点。它不会发生在阿拉巴马州。

当我使用表达式时:

response.xpath('//tr[@class="o" or @class="e"][2]/descendant::*/text()').extract()

为了提取文本,这个空节点将被忽略。

但我必须遵守格式。那么如何将这个空节点设置为空格呢?

顺便问一下,谁能有更好的解决方案来用scrapy抓取这个页面?

http://www.statoids.com/uus.html

【问题讨论】:

  • 阿拉巴马州 US.AL US01 Ala. -6~ 4,779,736 133,916 51,705 2 蒙哥马利 阿拉巴马 350-369 tr> 阿拉斯加 US.AK US02 -9~ 710,231 1,530,700 591,007 6 朱诺 阿拉斯加 995-999

标签: python html xpath web-scraping scrapy


【解决方案1】:

我会在这里尽可能明确并以“按列”的方式获取数据:

for state in response.xpath('//tr[@class="o" or @class="e"]'):
    item = State()
    item["hasc"] = state.xpath(".//td[2]/code/text()").extract()
    ...
    yield item

State 是你的 Item 类。请注意,extract() 会返回一个list。将item loader 与TakeFirst 或Join 处理器一起使用将帮助您在项目字段中包含字符串值。

【讨论】:

    【解决方案2】:

    您可以选择没有文本或子元素的空元素

    \*[not(text()) and not(*)] 
    

    所以选择空元素的 XPATH 将是

    //tr[@class='o' or @class='e'][2]/descendant::*[not(text()) and not(*)] 
    

    如果我们想得到一个值为 "Empty" 的字符串,我们可以附加 concat 方法

    //tr[@class='o' or @class='e'][2]/descendant::*[not(text()) and not(*)]/concat(.,'Empty')
    

    所以最后你可以 | 使用获得非空单元格的那个

    response.xpath('//tr[@class="o" or @class="e"][2]/descendant::*/text() | //tr[@class="o" or @class="e"][2]/descendant::*[not(text()) and not(*)]/concat(.,"Empty")).extract()
    

    我希望这会有所帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多