首页 > 解决方案 > 如何使用 CSS 获取信息?

问题描述

我尝试在scrapy shell中使用CSS:response.css('#fq9 .answer-options td::text').get()

回应:'\xa0'。如何删除它?

<td class="answer">
  <table class="answer-options">
    <tbody>
      <tr>
        <td>&nbsp;</td>
      </tr>
    </tbody>
  </table>
</td>

刮板.py

def profile(self, response):
    yield {'Company Name': response.css('#fq9 .answer-options td::text').get()}

标签: pythonhtmlcssscrapy

解决方案


  • 因为   基本上是一个花哨的空白,你可以使用.strip() docs
  • 如果没有适合 CSS 选择器的内容,您将None获得Company Name. 如果您添加像.get().strip(). 考虑None首先检查:

    def profile(self, response):
        out = response.css('#fq9 .answer-options td::text').get()
        if out is not None:
            yield {'Company Name': out.strip()}
    

编辑:您似乎有多个具有不同#fq索引的字段。您可以在解析之前对名称和索引进行分组,这将允许您使用循环:

def profile(self, response):
    fields = {
        'field1': 1,
        'field3': 3,
        'Company Name': 9
    }
    for name in fields:
        value = response.css('#fq{} .answer-options td::text'.format(fields[name])).get()
        if value is not None:
            yield {name: value.strip()}

推荐阅读