scrapy 2.3 將選擇器與正則表達式一起用

2021-06-09 10:07 更新

?Selector? 也有 ?.re()? 使用正則表達式提取數(shù)據(jù)的方法。但是,與使用不同 ?.xpath()? 或 ?.css()? 方法, ?.re()? 返回字符串列表。所以你不能構造嵌套的 ?.re()? 電話。

下面是一個用于從 HTML code 以上:

>>> response.xpath('//a[contains(@href, "image")]/text()').re(r'Name:\s*(.*)')
['My image 1',
 'My image 2',
 'My image 3',
 'My image 4',
 'My image 5']

另外還有一個助手在做往復運動 ?.get()? (及其別名) ?.extract_first()? 為 ?.re()? 命名 ?.re_first()? . 使用它只提取第一個匹配字符串:

>>> response.xpath('//a[contains(@href, "image")]/text()').re_first(r'Name:\s*(.*)')
'My image 1'
以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號