我尝试在scratchshell中使用CSS:response.css('#fq9 .answer-options td::text').get()
响应:'xa0'
。如何移除?
<td class="answer">
<table class="answer-options">
<tbody>
<tr>
<td> </td>
</tr>
</tbody>
</table>
</td>
刮刀.py
def profile(self, response):
yield {'Company Name': response.css('#fq9 .answer-options td::text').get()}
- 因为 基本上是一个可以使用
.strip()
文档的花哨空白 -
如果没有适合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()}
Edit:您似乎有多个字段具有不同的#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()}