scrapy 2.3 嵌套裝載機

2021-06-07 15:58 更新

從文檔的子部分分析相關(guān)值時,創(chuàng)建嵌套加載器可能很有用。假設(shè)您正在從一個頁面的頁腳提取細節(jié),該頁面的外觀如下:

例子::

<footer>
    <a class="social"  rel="external nofollow" target="_blank" >Like Us</a>
    <a class="social"  rel="external nofollow" target="_blank" >Follow Us</a>
    <a class="email" href="mailto:whatever@example.com">Email Us</a>
</footer>

如果沒有嵌套加載程序,則需要為要提取的每個值指定完整的xpath(或css)。

例子::

loader = ItemLoader(item=Item())
# load stuff not in the footer
loader.add_xpath('social', '//footer/a[@class = "social"]/@href')
loader.add_xpath('email', '//footer/a[@class = "email"]/@href')
loader.load_item()

相反,您可以使用頁腳選擇器創(chuàng)建嵌套加載程序,并添加相對于頁腳的值。功能相同,但避免重復(fù)頁腳選擇器。

例子::

loader = ItemLoader(item=Item())
# load stuff not in the footer
footer_loader = loader.nested_xpath('//footer')
footer_loader.add_xpath('social', 'a[@class = "social"]/@href')
footer_loader.add_xpath('email', 'a[@class = "email"]/@href')
# no need to call footer_loader.load_item()
loader.load_item()

您可以任意嵌套加載程序,它們可以使用xpath或css選擇器。作為一般準則,當嵌套加載器使您的代碼更簡單,但不要過度嵌套,否則您的解析器可能會變得難以讀取。

以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號