W3Cschool
恭喜您成為首批注冊用戶
獲得88經(jīng)驗值獎勵
從文檔的子部分分析相關(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選擇器。作為一般準則,當嵌套加載器使您的代碼更簡單,但不要過度嵌套,否則您的解析器可能會變得難以讀取。
Copyright©2021 w3cschool編程獅|閩ICP備15016281號-3|閩公網(wǎng)安備35020302033924號
違法和不良信息舉報電話:173-0602-2364|舉報郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號
聯(lián)系方式:
更多建議: