提取內容

我們在 Scrapy 的 shell 中展示如何從網頁提取數據:

scrapy shell "http://quotes.toscrape.com/page/1/"

注意:windows 系統下 url 需要用雙引號。

你會看到這樣的輸出:

2017-06-14 21:26:03 [scrapy.core.engine] DEBUG: Crawled (200) <GET http://quotes.toscrape.com/page/1/> (referer: None)
[s] Available Scrapy objects:
[s]   scrapy     scrapy module (contains scrapy.Request, scrapy.Selector, etc)
[s]   crawler    <scrapy.crawler.Crawler object at 0x01047E90>
[s]   item       {}
[s]   request    <GET http://quotes.toscrape.com/page/1/>
[s]   response   <200 http://quotes.toscrape.com/page/1/>
[s]   settings   <scrapy.settings.Settings object at 0x0427C310>
[s]   spider     <DefaultSpider 'default' at 0x4e43af0>
[s] Useful shortcuts:
[s]   fetch(url[, redirect=True]) Fetch URL and update local objects (by default, redirects are followed)
[s]   fetch(req)                  Fetch a scrapy.Request and update local objects
[s]   shelp()           Shell help (print this help)
[s]   view(response)    View response in a browser
>>>

下面我們在 shell 里面利用 css 選擇器來提取網頁的數據:

>>> response.css('title')
[<Selector xpath='descendant-or-self::title' data='<title>Quotes to Scrape</title>'>]

執行上述命令將會返回一個類似列表的對象:SelectorList;這是由選擇器根據提取規則提取出來的 XML/HTML 元素,你可以對它進一步細分或提取。

要提取 <title> 標簽里面的內容,可以這樣:

>>> response.css('title::text').extract()
['Quotes to Scrape']

在 css 選擇器表達式中使用 ::text,可以提取標簽的內容,如果不使用,結果如下:

>>> response.css('title').extract()
['<title>Quotes to Scrape</title>']

.extract() 方法會根據 SelectorList 內容返回一個列表,如果我們只需要返回列表中第一個元素,或者知道列表中只存在一個元素,可以這樣寫:

>>> response.css('title::text').extract_first()
'Quotes to Scrape'

又或者,可以用列表切片的方式:

>>> response.css('title::text')[0].extract()
'Quotes to Scrape'

但我們還是建議采用 .extract_first(),這樣可以避免要提取的元素為空的時候發生 IndexError

除了上述方法外,我們還可以用正則表達式提取元素,用 re() 方法即可:

>>> response.css('title::text').re(r'Quotes.*')
['Quotes to Scrape']

>>> response.css('title::text').re(r'Q\w+')
['Quotes']

>>> response.css('title::text').re(r'(\w+) to (\w+)')
['Quotes', 'Scrape']

Scrapy 還能用 Xpath 來提取內容:

>>> response.xpath('//title')
[<Selector xpath='//title' data='<title>Quotes to Scrape</title>'>]

>>> response.xpath('//title/text()').extract_first()
'Quotes to Scrape'
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容