拓冰建站拓冰建站
首页 / 资讯中心 / 正文

Scrapling 如何用 SitemapSpider 基于 sitemap 自动发现并爬取整个站点

Scrapling 如何用 SitemapSpider 基于 sitemap 自动发现并爬取整个站点【免费下载链接】Scrapling️ An adaptive Web Scraping framework that handles everything from a single request to a full-scale crawl!项目地址: https://gitcode.com/GitHub_Trending/sc/Scrapling当你拿到一个站点的 sitemap.xml想把它列出的所有页面批量抓下来但又不想为每一类 URL 手写parse()样板代码时Scrapling 的 spider 系统提供了现成的SitemapSpider模板你只需声明sitemap_urls和一组基于LinkExtractor的规则它会自动解析 sitemap包括 sitemap 索引把每个 URL 分发给第一个匹配的回调处理。本文按「安装 → 编写 spider → 运行 → 验证结果」的顺序走通这条路径并覆盖 sitemap 索引、robots.txt 入口和多语言 alternate URL 三个可选分支。前提条件Python 3.10 或更高版本。安装spider 功能需要 fetchers 依赖Scrapling 的裸装命令只包含解析引擎不包含 fetchers 和 spiders 所需的依赖此时importscrapling.spiders会抛ModuleNotFoundErrorpip install scrapling使用 spider包括SitemapSpider前必须安装 fetchers 依赖pip install scrapling[fetchers] scrapling install # 下载浏览器及其系统依赖 scrapling install --force # 强制重装scrapling install会下载所有浏览器及其系统依赖和指纹操作依赖如果只走 HTTP 请求这一步也是 fetchers 安装流程的一部分。安装完成后from scrapling.spiders import SitemapSpider才能正常导入。SitemapSpider 如何分发 sitemap 里的 URL理解分发规则才能解释为什么某些 URL 没有出现在结果里。SitemapSpider继承自Spider内部机制见 generic-templates.md 与 sitemap.pystart_urls被换成sitemap_urls未设置sitemap_urls时start_requests()直接抛出RuntimeErrorSitemapSpider needs sitemap_urls to be set.。每个 sitemap URL 先由内部的_parse_sitemap回调解析。遇到sitemapindexsitemap 的 sitemap时自动递归下载每个子 sitemap遇到urlset时提取每个url的loc。gzip 压缩的 sitemap.xml.gz或 gzip content-type会被自动解压XML 解析失败只记录一条 warning如 Failed to parse sitemap XML不会中断整个爬取。拿到 URL 列表后SitemapSpider按顺序用每条规则的LinkExtractor.matches(url)逐个检查第一个匹配的规则获胜该 URL 以这条规则的 callback 发出请求。有规则但没有任何规则匹配该 URL 被丢弃。rules()返回空列表所有 URL 路由到 spider 的parse()方法parse()默认实现会抛NotImplementedError所以要么写规则要么自己覆写parse()。LinkExtractor的 URL 过滤参数来自 generic-templates.md 的参数表参数默认值说明allow()保留的 URL 模式空表示匹配全部deny()丢弃的 URL 模式永远优先于allowallow_domains()保留的主机名子域自动匹配deny_domains()丢弃的主机名deny_extensionsIGNORED_EXTENSIONS丢弃的文件扩展名pdf、zip、图片、视频等注意deny_extensions有默认值即使allow匹配带 pdf、zip、图片等扩展名的 sitemap URL 也会被丢弃。编写并运行一个 SitemapSpider以下代码结构来自 generic-templates.md 的官方示例。使用前需要替换sitemap_urls换成目标站点的真实 sitemap 地址rules()里的allow正则和回调选择器按你的站点结构调整。from scrapling.spiders import SitemapSpider, CrawlRule, LinkExtractor class MySitemap(SitemapSpider): name sm sitemap_urls [https://example.com/sitemap.xml] def rules(self): return [ CrawlRule(LinkExtractor(allowr/posts/), callbackself.parse_post), CrawlRule(LinkExtractor(allowr/products/), callbackself.parse_product), ] async def parse_post(self, response): yield {title: response.css(h1::text).get()} async def parse_product(self, response): yield {sku: response.css(.sku::text).get()} result MySitemap().start()几个要点回调必须是 async generatorasync defyield与普通Spider一致。CrawlRule除callback外还支持可选的priority覆盖和process_request在请求发出前修改它。start()内部处理全部异步机制爬取过程会记录到终端结束后返回CrawlResult对象。验证爬取结果start()返回的CrawlResult是判断是否成功的依据见 getting-started.mdresult MySitemap().start() # 爬完还是被暂停了 print(fCompleted: {result.completed}) # 访问抓到的条目 for item in result.items: print(item) # 查看统计 print(fScraped {result.stats.items_scraped} items) print(fMade {result.stats.requests_count} requests) print(fFailed: {result.stats.failed_requests_count}) print(fTook {result.stats.elapsed_seconds:.1f} seconds)条目可以用内置方法直接导出父目录不存在时会自动创建result.items.to_json(sm.json, indentTrue) # JSON result.items.to_jsonl(sm.jsonl) # 每行一个 JSON 对象 result.items.to_csv(sm.csv) # CSV result.items.to_xml(sm.xml) # XML判断爬取是否正常看三件事result.completed是否为TrueFalse且result.paused为True说明被 CtrlC 暂停可重新运行恢复stats.failed_requests_count有多少失败请求stats.items_scraped是否接近你预期的 sitemap 条目数。如果发现 sitemap 里的 URL 数量明显多于实际请求数通常是有 URL 没匹配任何规则被丢弃了回去检查rules()的allow正则和deny_extensions默认过滤。完整统计清单状态码分布、被 robots.txt 拦截数、按域的字节数等见 advanced.md 的 Results Statistics 一节。可选分支三种 sitemap 入口与过滤只爬部分子 sitemapsitemap 索引当根 sitemap 是sitemapindex时SitemapSpider默认递归进入所有子 sitemap。用sitemap_follow指定一个LinkExtractor只进入匹配的子 sitemapNone表示进入全部class MySitemap(SitemapSpider): name sm sitemap_urls [https://example.com/sitemap.xml] sitemap_follow LinkExtractor(allowr/posts-sitemap-\d\.xml) # 只进文章 sitemap用 robots.txt 作为入口把 robots.txt 地址直接放进sitemap_urlsSitemapSpider会识别它提取其中所有Sitemap:指令并逐个跟进class MySitemap(SitemapSpider): name sm sitemap_urls [https://example.com/robots.txt]如果 robots.txt 里没有 Sitemap 指令会记录一条 No Sitemaps found in ... 的 warning爬取不会拿到任何 URL。爬多语言版本页面设置sitemap_alternate_links Truexhtml:link relalternate hreflang...中的地址也会被提取并同样走rules()分发class MySitemap(SitemapSpider): name sm sitemap_urls [https://example.com/sitemap.xml] sitemap_alternate_links True限制与边界未设置sitemap_urls会直接抛RuntimeError不存在其他默认入口。有规则时不匹配任何规则的 sitemap URL 被静默丢弃sitemap 里的 PDF、图片等静态资源 URL 受deny_extensions默认值影响同样会被丢弃。sitemap 本身损坏gzip 解压失败或 XML 语法错误只产生 warning 并跳过该 sitemap需要到爬取日志里找 Failed to decompress sitemap / Failed to parse sitemap XML 来定位是哪个 sitemap 没被解析。如果站点还有 robots.txt 抓取限制可以像普通 spider 一样设置robots_txt_obey True被 Disallow 的请求会计入stats.robots_disallowed_count。大站点爬取被中断时可通过构造参数crawldir启用检查点机制暂停/恢复、断点续爬用法见 advanced.md 的 Pause Resume 一节。更多 spider 能力并发控制concurrent_requests/download_delay、AutoThrottle、流式输出stream()、生命周期钩子参考 advanced.md如果不用模板、想在自己的Spider.parse()里直接取链接LinkExtractor也可以单独使用示例同在 generic-templates.md。【免费下载链接】Scrapling️ An adaptive Web Scraping framework that handles everything from a single request to a full-scale crawl!项目地址: https://gitcode.com/GitHub_Trending/sc/Scrapling创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考
分享:

看完干货,该让你的企业上线了

免费需求沟通 · 48 小时内出具建站方案 · 河南本地可上门