python - 如何使用 CSS 获取信息?
问题描述
我尝试在scrapy shell中使用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()
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()}
推荐阅读
- python - 有没有办法向量化这个函数或提高它的效率
- google-workspace - 已解决 - SDK 中的商品详情中缺少“英文”详细信息
- mongodb - 如何更新匹配某些 mongoDB 条件的四分之一决赛数组中的第一个对象?
- connection - 从 CENTOS 7 连接到 Oracle 数据库时出错
- button - 如何在加载下一个屏幕之前停止我的页面冻结?
- java - 无法在tomcat上部署spring boot app
- c# - 将 MySql 与实体框架 c# 连接起来
- ios - 为什么我没有从 Amadeus Airport and City Search API (iOS) 取回数据?
- c++ - void 参数上模板特化的 C++ 类型推导失败
- .htaccess - 为什么我的 htaccess 代码强制 http 不起作用?