Python 网页抓取撞上 403 和空页面?Scrapling 用 3 个 Fetcher 把静态、动态、强反爬一次抓完
【免费下载链接】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
用 requests 抓个列表页被 403 拦下,换个 JS 渲染的站点,<body>里只剩骨架屏——Python 网页抓取的第一道坎就是反爬和动态页面渲染。Scrapling 就是为这两种情况做的:三个 Fetcher 分别对应静态、动态、强反爬页面,从单次请求到批量抓取一个库覆盖。
🐢 30 秒跑起来
这一节解决环境问题,两行装好,三行出结果:
git clone https://gitcode.com/GitHub_Trending/sc/Scrapling cd Scrapling && pip install -e .from scrapling.fetchers import Fetcher page = Fetcher.get('https://example.com') print(page.css_first('title') # 返回选择器对象,直接取文本或属性 )返回的page本身就带解析能力,不用再引入 BeautifulSoup。
📄 静态页面直接取数
这一节解决普通 HTML 页面的取数和选择器写法。
from scrapling.fetchers import Fetcher page = Fetcher.get('https://example.com') print(page.css_first('.title').text) # CSS 选择器 print(page.xpath_first('//h1').text) # XPath 选择器页面结构偶尔改版时,可以打开 adaptive 模式:选择器失效后它按之前记录的特征自动重定位元素,不用每次改代码。选择器写法详见 选择器文档。
另一个省事的功能在 CLI/shell 里:浏览器 DevTools 里复制的 cURL 命令可以直接粘进 scrapling 执行,headers、cookie 自动还原,不用手工翻译请求。
⏳ 动态页面怎么等
这一节解决"页面还没渲染完就取数、结果全是空"的问题。
from scrapling.fetchers import DynamicFetcher page = DynamicFetcher.fetch( 'https://dynamic-site.com', network_idle=True, # 等网络空闲 wait_selector='.product-card', # 或等目标元素出现 ) print(page.css_first('.product-card').text)network_idle等请求停掉再返回,wait_selector等指定选择器出现才继续。两个参数二选一即可,取数时机由页面决定,比固定time.sleep稳,也不会多等无谓的时间。参数全集见 动态抓取文档。
🥷 隐身模式参数怎么配
这一节解决 Cloudflare 拦截、指纹检测这类强反爬站点。
from scrapling.fetchers import StealthyFetcher page = StealthyFetcher.fetch( 'https://protected-site.com', headless=True, solve_cloudflare=True, # 自动过 Cloudflare 挑战 humanize=True, # 拟人化输入与行为 geoip=True, # 指纹与代理出口 IP 保持一致 )solve_cloudflare会自动处理 Turnstile 等挑战;humanize模拟人类操作节奏,geoip保证指纹和出口 IP 自洽——这几项配合起来能过掉大多数基于指纹的检测。更轻的场景下,scrapling.engines.toolbelt.fingerprints里的generate_headers可以直接生成一组浏览器风格请求头,传给Fetcher.get的headers参数就能用。
📦 批量抓取怎么组织
这一节解决几十个 URL 的循环请求与失败重试。
from scrapling.fetchers import FetcherSession urls = [f'https://example.com/page/{i}' for i in range(10)] with FetcherSession(retries=3, retry_delay=1) as session: for url in urls: try: page = session.get(url) print(page.status, len(page.body)) except Exception as e: print('跳过:', url, e)FetcherSession复用连接并共享 cookie,retries和retry_delay是内置的重试与退避;外层再包一层 try/except,单个 URL 挂了不影响整批。更大的并发规模、断点续抓和自动代理轮换,走它自带的 spider 框架:
✅ 上手注意
这一节是踩坑清单,三条:
- headless 快但特征更明显;过不了检测时加
humanize,或临时开 headed 模式定位原因 - 动态页一律优先
wait_selector,固定 sleep 只会在页面变慢时翻车 - 先确认状态码再解析:403/429 说明换 Fetcher 或加代理,而不是改选择器
🧭 边界一句
Scrapling 适合单次请求到并发爬虫之间的绝大多数取数场景;它不替你判断某份数据能不能拿,付费接口、需要人工输入的验证码流程也不在覆盖范围内。
从Fetcher.get一行取静态页,到StealthyFetcher配齐隐身参数,中间不用换库、不用拼依赖,按上面三个 Fetcher 对号入座就行。抓之前先看一眼目标站的 robots.txt 和使用条款——能拿和该不该拿是两件事。
【免费下载链接】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),仅供参考