我正在逐行处理一个表,并且需要嗅探这些行的id
:
<table id="tbl">
<tr id="row_1">
<td id="cell_1">...</td>
</tr>
<tr id="row_2">
<td id="cell_2">...</td>
</tr>
</table>
所以我的代码看起来像这样:
def parse_table(self, response):
rows = response.css('#tbl > tr')
for row in rows:
rowid = row.css('::attr(id)')
if rowid.extract_first().startswith('row'):
...
但是,通过这种方式,第二次调用.css()
会给出row
的所有后代的ID,而不仅仅是它的直接子代的ID。也就是说,对于上面的示例超文本标记语言,它返回"row_1"
和"cell_1"
。如何限定链式css()
调用的作用域,使其只作用于给定行的直接子对象?
我尝试过使用Scrapy伪类,但是:scope
似乎不支持,并且:root
没有给我任何结果。
或者,我可以不通过CSS直接获取id
属性的值吗?
发布于 2018-07-22 08:20:24
我可以向您展示如何使用XPath完成相同的任务:
def parse_table(self, response):
for row in response.xpath('//*[@id="tbl"]/tr'):
rowid = row.xpath('./@id').extract_first()
if rowid.startswith('row'):
...
https://stackoverflow.com/questions/51460889
复制相似问题