爬虫蜘蛛项目加载器Item Loader类详解之嵌套加载器详解 (22)python SCRAPY最新教程1.51以上版本
解析文档子节中的相关值时,创建嵌套加载器会很有用。想象一下,您从页面的页脚中提取详细信息,如下所示:
例:
<footer> <a href="https://facebook.com/whatever">Like Us</a> <a href="https://twitter.com/whatever">Follow Us</a> <a href="mailto:[email protected]">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()
相反,您可以使用页脚选择器创建嵌套加载程序并添加相对于页脚的值。功能相同但您避免重复页脚选择器。
例:
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选择器。作为一般准则,当它们使代码更简单时使用嵌套的加载器但是不要过度嵌套或者解析器变得难以阅读。
本站所发布的一切资源仅限用于学习和研究目的;不得将上述内容用于商业或者非法用途,否则,一切后果请用户自负。本站信息来自网络,版权争议与本站无关。您必须在下载后的24个小时之内,从您的电脑中彻底删除上述内容。如果您喜欢该程序,请支持正版软件,购买注册,得到更好的正版服务。如果侵犯你的利益,请发送邮箱到 [email protected],我们会很快的为您处理。