docs: Add AI translations to other languages
This commit is contained in:
@@ -1,3 +1,6 @@
|
||||
Automated translations: [العربيه](README_AR.md) | [Español](README_ES.md) | [Deutsch](README_DE.md) | [简体中文](README_CN.md) | [日本語](README_JP.md) | [Русский](README_RU.md)
|
||||
|
||||
|
||||
<p align=center>
|
||||
<br>
|
||||
<a href="https://scrapling.readthedocs.io/en/latest/" target="_blank"><img src="https://raw.githubusercontent.com/D4Vinci/Scrapling/main/images/poster.png" style="width: 50%; height: 100%;" alt="main poster"/></a>
|
||||
@@ -0,0 +1,332 @@
|
||||
<p align=center>
|
||||
<br>
|
||||
<a href="https://scrapling.readthedocs.io/en/latest/" target="_blank"><img src="https://raw.githubusercontent.com/D4Vinci/Scrapling/main/images/poster.png" style="width: 50%; height: 100%;" alt="main poster"/></a>
|
||||
<br>
|
||||
<i><code>استخراج بيانات الويب بسهولة ويسر كما يجب أن يكون!</code></i>
|
||||
</p>
|
||||
<p align="center">
|
||||
<a href="https://github.com/D4Vinci/Scrapling/actions/workflows/tests.yml" alt="Tests">
|
||||
<img alt="Tests" src="https://github.com/D4Vinci/Scrapling/actions/workflows/tests.yml/badge.svg"></a>
|
||||
<a href="https://badge.fury.io/py/Scrapling" alt="PyPI version">
|
||||
<img alt="PyPI version" src="https://badge.fury.io/py/Scrapling.svg"></a>
|
||||
<a href="https://pepy.tech/project/scrapling" alt="PyPI Downloads">
|
||||
<img alt="PyPI Downloads" src="https://static.pepy.tech/personalized-badge/scrapling?period=total&units=INTERNATIONAL_SYSTEM&left_color=GREY&right_color=GREEN&left_text=Downloads"></a>
|
||||
<br/>
|
||||
<a href="https://discord.gg/EMgGbDceNQ" alt="Discord" target="_blank">
|
||||
<img alt="Discord" src="https://img.shields.io/discord/1360786381042880532?style=social&logo=discord&link=https%3A%2F%2Fdiscord.gg%2FEMgGbDceNQ">
|
||||
</a>
|
||||
<a href="https://x.com/Scrapling_dev" alt="X (formerly Twitter)">
|
||||
<img alt="X (formerly Twitter) Follow" src="https://img.shields.io/twitter/follow/Scrapling_dev?style=social&logo=x&link=https%3A%2F%2Fx.com%2FScrapling_dev">
|
||||
</a>
|
||||
<br/>
|
||||
<a href="https://pypi.org/project/scrapling/" alt="Supported Python versions">
|
||||
<img alt="Supported Python versions" src="https://img.shields.io/pypi/pyversions/scrapling.svg"></a>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<a href="https://scrapling.readthedocs.io/en/latest/parsing/selection/">
|
||||
طرق الاختيار
|
||||
</a>
|
||||
·
|
||||
<a href="https://scrapling.readthedocs.io/en/latest/fetching/choosing/">
|
||||
اختيار الجالب
|
||||
</a>
|
||||
·
|
||||
<a href="https://scrapling.readthedocs.io/en/latest/cli/overview/">
|
||||
واجهة سطر الأوامر
|
||||
</a>
|
||||
·
|
||||
<a href="https://scrapling.readthedocs.io/en/latest/ai/mcp-server/">
|
||||
وضع MCP
|
||||
</a>
|
||||
·
|
||||
<a href="https://scrapling.readthedocs.io/en/latest/tutorials/migrating_from_beautifulsoup/">
|
||||
الانتقال من Beautifulsoup
|
||||
</a>
|
||||
</p>
|
||||
|
||||
**توقف عن محاربة أنظمة مكافحة الروبوتات. توقف عن إعادة كتابة المحددات بعد كل تحديث للموقع.**
|
||||
|
||||
Scrapling ليست مجرد مكتبة أخرى لاستخراج بيانات الويب. إنها أول مكتبة استخراج **تكيفية** تتعلم من تغييرات المواقع وتتطور معها. بينما تتعطل المكتبات الأخرى عندما تحدث المواقع بنيتها، يعيد Scrapling تحديد موقع عناصرك تلقائياً ويحافظ على عمل أدوات الاستخراج الخاصة بك.
|
||||
|
||||
مبني للويب الحديث، يتميز Scrapling **بمحرك تحليل سريع خاص به** وجوالب للتعامل مع جميع تحديات استخراج بيانات الويب التي تواجهها أو ستواجهها. مبني بواسطة مستخرجي الويب لمستخرجي الويب والمستخدمين العاديين، هناك شيء للجميع.
|
||||
|
||||
```python
|
||||
>> from scrapling.fetchers import Fetcher, AsyncFetcher, StealthyFetcher, DynamicFetcher
|
||||
>> StealthyFetcher.adaptive = True
|
||||
# احصل على كود المصدر للمواقع بشكل خفي!
|
||||
>> page = StealthyFetcher.fetch('https://example.com', headless=True, network_idle=True)
|
||||
>> print(page.status)
|
||||
200
|
||||
>> products = page.css('.product', auto_save=True) # استخرج البيانات التي تنجو من تغييرات تصميم الموقع!
|
||||
>> # لاحقاً، إذا تغيرت بنية الموقع، مرر `adaptive=True`
|
||||
>> products = page.css('.product', adaptive=True) # و Scrapling لا يزال يجدها!
|
||||
```
|
||||
|
||||
# الرعاة
|
||||
|
||||
<!-- sponsors -->
|
||||
|
||||
<a href="https://www.scrapeless.com/en?utm_source=official&utm_term=scrapling" target="_blank" title="Effortless Web Scraping Toolkit for Business and Developers"><img src="https://raw.githubusercontent.com/D4Vinci/Scrapling/main/images/scrapeless.jpg"></a>
|
||||
<a href="https://evomi.com?utm_source=github&utm_medium=banner&utm_campaign=d4vinci-scrapling" target="_blank" title="Evomi is your Swiss Quality Proxy Provider, starting at $0.49/GB"><img src="https://raw.githubusercontent.com/D4Vinci/Scrapling/main/images/evomi.png"></a>
|
||||
<a href="https://visit.decodo.com/Dy6W0b" target="_blank" title="Try the Most Efficient Residential Proxies for Free"><img src="https://raw.githubusercontent.com/D4Vinci/Scrapling/main/images/decodo.png"></a>
|
||||
<a href="https://petrosky.io/d4vinci" target="_blank" title="PetroSky delivers cutting-edge VPS hosting."><img src="https://raw.githubusercontent.com/D4Vinci/Scrapling/main/images/petrosky.png"></a>
|
||||
<a href="https://app.cyberyozh.com/?utm_source=github&utm_medium=scrapling" target="_blank" title="We have gathered the best solutions for multi‑accounting and automation in one place."><img src="https://raw.githubusercontent.com/D4Vinci/Scrapling/main/images/cyberyozh.png"></a>
|
||||
<a href="https://www.swiftproxy.net/" target="_blank" title="Unlock Reliable Proxy Services with Swiftproxy!"><img src="https://raw.githubusercontent.com/D4Vinci/Scrapling/main/images/swiftproxy.png"></a>
|
||||
<a href="https://www.rapidproxy.io/?ref=d4v" target="_blank" title="Affordable Access to the Proxy World – bypass CAPTCHAs blocks, and avoid additional costs."><img src="https://raw.githubusercontent.com/D4Vinci/Scrapling/main/images/rapidproxy.jpg"></a>
|
||||
<a href="https://serpapi.com/?utm_source=scrapling" target="_blank" title="Scrape Google and other search engines with SerpApi"><img src="https://raw.githubusercontent.com/D4Vinci/Scrapling/main/images/SerpApi.png"></a>
|
||||
|
||||
<!-- /sponsors -->
|
||||
|
||||
<i><sub>هل تريد عرض إعلانك هنا؟ انقر [هنا](https://github.com/sponsors/D4Vinci) واختر المستوى الذي يناسبك!</sub></i>
|
||||
|
||||
---
|
||||
|
||||
## الميزات الرئيسية
|
||||
|
||||
### جلب متقدم للمواقع مع دعم الجلسات
|
||||
- **طلبات HTTP**: طلبات HTTP سريعة وخفية مع فئة `Fetcher`. يمكنها تقليد بصمة TLS للمتصفح والرؤوس واستخدام HTTP3.
|
||||
- **التحميل الديناميكي**: جلب المواقع الديناميكية مع أتمتة كاملة للمتصفح من خلال فئة `DynamicFetcher` التي تدعم Chromium من Playwright، وChrome الحقيقي، ووضع التخفي المخصص.
|
||||
- **تجاوز مكافحة الروبوتات**: قدرات تخفي متقدمة مع `StealthyFetcher` باستخدام نسخة معدلة من Firefox وانتحال البصمات. يمكنه تجاوز جميع أنواع Turnstile وInterstitial من Cloudflare بسهولة بالأتمتة.
|
||||
- **إدارة الجلسات**: دعم الجلسات المستمرة مع فئات `FetcherSession` و`StealthySession` و`DynamicSession` لإدارة ملفات تعريف الارتباط والحالة عبر الطلبات.
|
||||
- **دعم Async**: دعم async كامل عبر جميع الجوالب وفئات الجلسات async المخصصة.
|
||||
|
||||
### الاستخراج التكيفي والتكامل مع الذكاء الاصطناعي
|
||||
- 🔄 **تتبع العناصر الذكي**: إعادة تحديد موقع العناصر بعد تغييرات الموقع باستخدام خوارزميات التشابه الذكية.
|
||||
- 🎯 **الاختيار المرن الذكي**: محددات CSS، محددات XPath، البحث القائم على الفلاتر، البحث النصي، البحث بالتعبيرات العادية والمزيد.
|
||||
- 🔍 **البحث عن عناصر مشابهة**: تحديد العناصر المشابهة للعناصر الموجودة تلقائياً.
|
||||
- 🤖 **خادم MCP للاستخدام مع الذكاء الاصطناعي**: خادم MCP مدمج لاستخراج بيانات الويب بمساعدة الذكاء الاصطناعي واستخراج البيانات. يتميز خادم MCP بقدرات مخصصة قوية تستخدم Scrapling لاستخراج المحتوى المستهدف قبل تمريره إلى الذكاء الاصطناعي (Claude/Cursor/إلخ)، وبالتالي تسريع العمليات وتقليل التكاليف عن طريق تقليل استخدام الرموز. ([فيديو توضيحي](https://www.youtube.com/watch?v=qyFk3ZNwOxE))
|
||||
|
||||
### بنية عالية الأداء ومختبرة في المعارك
|
||||
- 🚀 **سريع كالبرق**: أداء محسّن يتفوق على معظم مكتبات استخراج Python.
|
||||
- 🔋 **فعال في استخدام الذاكرة**: هياكل بيانات محسّنة وتحميل كسول لأقل استخدام للذاكرة.
|
||||
- ⚡ **تسلسل JSON سريع**: أسرع 10 مرات من المكتبة القياسية.
|
||||
- 🏗️ **مُختبر في المعارك**: لا يمتلك Scrapling فقط تغطية اختبار بنسبة 92٪ وتغطية كاملة لتلميحات الأنواع، ولكن تم استخدامه يومياً من قبل مئات مستخرجي الويب خلال العام الماضي.
|
||||
|
||||
### تجربة صديقة للمطورين/مستخرجي الويب
|
||||
- 🎯 **غلاف استخراج ويب تفاعلي**: غلاف IPython مدمج اختياري مع تكامل Scrapling، واختصارات، وأدوات جديدة لتسريع تطوير سكريبتات استخراج الويب، مثل تحويل طلبات curl إلى طلبات Scrapling وعرض نتائج الطلبات في متصفحك.
|
||||
- 🚀 **استخدمه مباشرة من الطرفية**: اختيارياً، يمكنك استخدام Scrapling لاستخراج عنوان URL دون كتابة سطر واحد من الكود!
|
||||
- 🛠️ **واجهة برمجة تطبيقات التنقل الغنية**: اجتياز DOM متقدم مع طرق التنقل بين الوالدين والأشقاء والأطفال.
|
||||
- 🧬 **معالجة نصوص محسّنة**: تعبيرات عادية مدمجة وطرق تنظيف وعمليات سلسلة محسّنة.
|
||||
- 📝 **إنشاء محدد تلقائي**: إنشاء محددات CSS/XPath قوية لأي عنصر.
|
||||
- 🔌 **واجهة برمجة تطبيقات مألوفة**: مشابه لـ Scrapy/BeautifulSoup مع نفس العناصر الزائفة المستخدمة في Scrapy/Parsel.
|
||||
- 📘 **تغطية كاملة للأنواع**: تلميحات نوع كاملة لدعم IDE ممتاز وإكمال الكود.
|
||||
- 🔋 **صورة Docker جاهزة**: مع كل إصدار، يتم بناء ودفع صورة Docker تحتوي على جميع المتصفحات تلقائياً.
|
||||
|
||||
## البدء
|
||||
|
||||
### الاستخدام الأساسي
|
||||
```python
|
||||
from scrapling.fetchers import Fetcher, StealthyFetcher, DynamicFetcher
|
||||
from scrapling.fetchers import FetcherSession, StealthySession, DynamicSession
|
||||
|
||||
# طلبات HTTP مع دعم الجلسات
|
||||
with FetcherSession(impersonate='chrome') as session: # استخدم أحدث إصدار من بصمة TLS لـ Chrome
|
||||
page = session.get('https://quotes.toscrape.com/', stealthy_headers=True)
|
||||
quotes = page.css('.quote .text::text')
|
||||
|
||||
# أو استخدم طلبات لمرة واحدة
|
||||
page = Fetcher.get('https://quotes.toscrape.com/')
|
||||
quotes = page.css('.quote .text::text')
|
||||
|
||||
# وضع التخفي المتقدم (احتفظ بالمتصفح مفتوحاً حتى تنتهي)
|
||||
with StealthySession(headless=True, solve_cloudflare=True) as session:
|
||||
page = session.fetch('https://nopecha.com/demo/cloudflare', google_search=False)
|
||||
data = page.css('#padded_content a')
|
||||
|
||||
# أو استخدم نمط الطلب لمرة واحدة، يفتح المتصفح لهذا الطلب، ثم يغلقه بعد الانتهاء
|
||||
page = StealthyFetcher.fetch('https://nopecha.com/demo/cloudflare')
|
||||
data = page.css('#padded_content a')
|
||||
|
||||
# أتمتة المتصفح الكاملة (احتفظ بالمتصفح مفتوحاً حتى تنتهي)
|
||||
with DynamicSession(headless=True) as session:
|
||||
page = session.fetch('https://quotes.toscrape.com/', network_idle=True)
|
||||
quotes = page.css('.quote .text::text')
|
||||
|
||||
# أو استخدم نمط الطلب لمرة واحدة
|
||||
page = DynamicFetcher.fetch('https://quotes.toscrape.com/', network_idle=True)
|
||||
quotes = page.css('.quote .text::text')
|
||||
```
|
||||
|
||||
### اختيار العناصر
|
||||
```python
|
||||
# محددات CSS
|
||||
page.css('a::text') # استخراج النص
|
||||
page.css('a::attr(href)') # استخراج السمات
|
||||
page.css('a', recursive=False) # العناصر المباشرة فقط
|
||||
page.css('a', auto_save=True) # حفظ مواضع العناصر تلقائياً
|
||||
|
||||
# XPath
|
||||
page.xpath('//a/text()')
|
||||
|
||||
# بحث مرن
|
||||
page.find_by_text('Python', first_match=True) # البحث بالنص
|
||||
page.find_by_regex(r'\d{4}') # البحث بنمط التعبير العادي
|
||||
page.find('div', {'class': 'container'}) # البحث بالسمات
|
||||
|
||||
# التنقل
|
||||
element.parent # الحصول على العنصر الوالد
|
||||
element.next_sibling # الحصول على الشقيق التالي
|
||||
element.children # الحصول على الأطفال
|
||||
|
||||
# عناصر مشابهة
|
||||
similar = page.get_similar(element) # البحث عن عناصر مشابهة
|
||||
|
||||
# الاستخراج التكيفي
|
||||
saved_elements = page.css('.product', auto_save=True)
|
||||
# لاحقاً، عندما يتغير الموقع:
|
||||
page.css('.product', adaptive=True) # البحث عن العناصر باستخدام المواضع المحفوظة
|
||||
```
|
||||
|
||||
### استخدام الجلسة
|
||||
```python
|
||||
from scrapling.fetchers import FetcherSession, AsyncFetcherSession
|
||||
|
||||
# جلسة متزامنة
|
||||
with FetcherSession() as session:
|
||||
# يتم الاحتفاظ بملفات تعريف الارتباط تلقائياً
|
||||
page1 = session.get('https://quotes.toscrape.com/login')
|
||||
page2 = session.post('https://quotes.toscrape.com/login', data={'username': 'admin', 'password': 'admin'})
|
||||
|
||||
# تبديل بصمة المتصفح إذا لزم الأمر
|
||||
page2 = session.get('https://quotes.toscrape.com/', impersonate='firefox135')
|
||||
|
||||
# استخدام جلسة async
|
||||
async with AsyncStealthySession(max_pages=2) as session:
|
||||
tasks = []
|
||||
urls = ['https://example.com/page1', 'https://example.com/page2']
|
||||
|
||||
for url in urls:
|
||||
task = session.fetch(url)
|
||||
tasks.append(task)
|
||||
|
||||
print(session.get_pool_stats()) # اختياري - حالة مجموعة علامات تبويب المتصفح (مشغول/حر/خطأ)
|
||||
results = await asyncio.gather(*tasks)
|
||||
print(session.get_pool_stats())
|
||||
```
|
||||
|
||||
## واجهة سطر الأوامر والغلاف التفاعلي
|
||||
|
||||
يتضمن Scrapling v0.3 واجهة سطر أوامر قوية:
|
||||
|
||||
[](https://asciinema.org/a/736339)
|
||||
|
||||
```bash
|
||||
# تشغيل غلاف استخراج الويب التفاعلي
|
||||
scrapling shell
|
||||
|
||||
# استخراج الصفحات إلى ملف مباشرة دون برمجة (يستخرج المحتوى داخل وسم `body` افتراضياً)
|
||||
# إذا انتهى ملف الإخراج بـ `.txt`، فسيتم استخراج محتوى النص للهدف.
|
||||
# إذا انتهى بـ `.md`، فسيكون تمثيل markdown لمحتوى HTML، و`.html` سيكون محتوى HTML مباشرة.
|
||||
scrapling extract get 'https://example.com' content.md
|
||||
scrapling extract get 'https://example.com' content.txt --css-selector '#fromSkipToProducts' --impersonate 'chrome' # جميع العناصر المطابقة لمحدد CSS '#fromSkipToProducts'
|
||||
scrapling extract fetch 'https://example.com' content.md --css-selector '#fromSkipToProducts' --no-headless
|
||||
scrapling extract stealthy-fetch 'https://nopecha.com/demo/cloudflare' captchas.html --css-selector '#padded_content a' --solve-cloudflare
|
||||
```
|
||||
|
||||
> [!NOTE]
|
||||
> هناك العديد من الميزات الإضافية، لكننا نريد إبقاء هذه الصفحة موجزة، مثل خادم MCP وغلاف استخراج الويب التفاعلي. تحقق من الوثائق الكاملة [هنا](https://scrapling.readthedocs.io/en/latest/)
|
||||
|
||||
## معايير الأداء
|
||||
|
||||
Scrapling ليس قوياً فقط - إنه أيضاً سريع بشكل مذهل، والتحديثات منذ الإصدار 0.3 قدمت تحسينات أداء استثنائية عبر جميع العمليات.
|
||||
|
||||
### اختبار سرعة استخراج النص (5000 عنصر متداخل)
|
||||
|
||||
| # | المكتبة | الوقت (ms) | vs Scrapling |
|
||||
|---|:-----------------:|:---------:|:------------:|
|
||||
| 1 | Scrapling | 1.92 | 1.0x |
|
||||
| 2 | Parsel/Scrapy | 1.99 | 1.036x |
|
||||
| 3 | Raw Lxml | 2.33 | 1.214x |
|
||||
| 4 | PyQuery | 20.61 | ~11x |
|
||||
| 5 | Selectolax | 80.65 | ~42x |
|
||||
| 6 | BS4 with Lxml | 1283.21 | ~698x |
|
||||
| 7 | MechanicalSoup | 1304.57 | ~679x |
|
||||
| 8 | BS4 with html5lib | 3331.96 | ~1735x |
|
||||
|
||||
### أداء تشابه العناصر والبحث النصي
|
||||
|
||||
قدرات العثور على العناصر التكيفية لـ Scrapling تتفوق بشكل كبير على البدائل:
|
||||
|
||||
| المكتبة | الوقت (ms) | vs Scrapling |
|
||||
|-------------|:---------:|:------------:|
|
||||
| Scrapling | 1.87 | 1.0x |
|
||||
| AutoScraper | 10.24 | 5.476x |
|
||||
|
||||
|
||||
> تمثل جميع المعايير متوسطات أكثر من 100 تشغيل. انظر [benchmarks.py](https://github.com/D4Vinci/Scrapling/blob/main/benchmarks.py) للمنهجية.
|
||||
|
||||
## التثبيت
|
||||
|
||||
يتطلب Scrapling Python 3.10 أو أعلى:
|
||||
|
||||
```bash
|
||||
pip install scrapling
|
||||
```
|
||||
|
||||
بدءاً من v0.3.2، يتضمن هذا التثبيت فقط محرك المحلل وتبعياته، بدون أي جوالب أو تبعيات سطر أوامر.
|
||||
|
||||
### التبعيات الاختيارية
|
||||
|
||||
1. إذا كنت ستستخدم أياً من الميزات الإضافية أدناه، أو الجوالب، أو فئاتها، فأنت بحاجة إلى تثبيت تبعيات الجوالب ثم تثبيت تبعيات المتصفح الخاصة بها بـ
|
||||
```bash
|
||||
pip install "scrapling[fetchers]"
|
||||
|
||||
scrapling install
|
||||
```
|
||||
|
||||
يقوم هذا بتنزيل جميع المتصفحات مع تبعيات النظام وتبعيات معالجة البصمات الخاصة بها.
|
||||
|
||||
2. ميزات إضافية:
|
||||
- تثبيت ميزة خادم MCP:
|
||||
```bash
|
||||
pip install "scrapling[ai]"
|
||||
```
|
||||
- تثبيت ميزات الغلاف (غلاف استخراج الويب وأمر `extract`):
|
||||
```bash
|
||||
pip install "scrapling[shell]"
|
||||
```
|
||||
- تثبيت كل شيء:
|
||||
```bash
|
||||
pip install "scrapling[all]"
|
||||
```
|
||||
تذكر أنك تحتاج إلى تثبيت تبعيات المتصفح مع `scrapling install` بعد أي من هذه الإضافات (إذا لم تكن قد فعلت ذلك بالفعل)
|
||||
|
||||
### Docker
|
||||
يمكنك أيضاً تثبيت صورة Docker مع جميع الإضافات والمتصفحات باستخدام الأمر التالي من DockerHub:
|
||||
```bash
|
||||
docker pull pyd4vinci/scrapling
|
||||
```
|
||||
أو تنزيلها من سجل GitHub:
|
||||
```bash
|
||||
docker pull ghcr.io/d4vinci/scrapling:latest
|
||||
```
|
||||
يتم بناء هذه الصورة ودفعها تلقائياً من خلال إجراءات GitHub على الفرع الرئيسي للمستودع.
|
||||
|
||||
## المساهمة
|
||||
|
||||
نرحب بالمساهمات! يرجى قراءة [إرشادات المساهمة](https://github.com/D4Vinci/Scrapling/blob/main/CONTRIBUTING.md) قبل البدء.
|
||||
|
||||
## إخلاء المسؤولية
|
||||
|
||||
> [!CAUTION]
|
||||
> يتم توفير هذه المكتبة للأغراض التعليمية والبحثية فقط. باستخدام هذه المكتبة، فإنك توافق على الامتثال لقوانين استخراج البيانات والخصوصية المحلية والدولية. المؤلفون والمساهمون غير مسؤولين عن أي إساءة استخدام لهذا البرنامج. احترم دائماً شروط خدمة المواقع وملفات robots.txt.
|
||||
|
||||
## الترخيص
|
||||
|
||||
هذا العمل مرخص بموجب ترخيص BSD-3-Clause.
|
||||
|
||||
## الشكر والتقدير
|
||||
|
||||
يتضمن هذا المشروع كوداً معدلاً من:
|
||||
- Parsel (ترخيص BSD) - يستخدم للوحدة الفرعية [translator](https://github.com/D4Vinci/Scrapling/blob/main/scrapling/core/translator.py)
|
||||
|
||||
## الشكر والمراجع
|
||||
|
||||
- العمل الرائع لـ [Daijro](https://github.com/daijro) على [BrowserForge](https://github.com/daijro/browserforge) و[Camoufox](https://github.com/daijro/camoufox)
|
||||
- العمل الرائع لـ [Vinyzu](https://github.com/Vinyzu) على [Botright](https://github.com/Vinyzu/Botright) و[PatchRight](https://github.com/Kaliiiiiiiiii-Vinyzu/patchright)
|
||||
- [brotector](https://github.com/kaliiiiiiiiii/brotector) لتقنيات تجاوز اكتشاف المتصفح
|
||||
- [fakebrowser](https://github.com/kkoooqq/fakebrowser) و[BotBrowser](https://github.com/botswin/BotBrowser) لأبحاث البصمات
|
||||
|
||||
---
|
||||
<div align="center"><small>مصمم ومصنوع بـ ❤️ بواسطة كريم شعير.</small></div><br>
|
||||
@@ -0,0 +1,332 @@
|
||||
<p align=center>
|
||||
<br>
|
||||
<a href="https://scrapling.readthedocs.io/en/latest/" target="_blank"><img src="https://raw.githubusercontent.com/D4Vinci/Scrapling/main/images/poster.png" style="width: 50%; height: 100%;" alt="main poster"/></a>
|
||||
<br>
|
||||
<i><code>简单、轻松的网页抓取,本该如此!</code></i>
|
||||
</p>
|
||||
<p align="center">
|
||||
<a href="https://github.com/D4Vinci/Scrapling/actions/workflows/tests.yml" alt="Tests">
|
||||
<img alt="Tests" src="https://github.com/D4Vinci/Scrapling/actions/workflows/tests.yml/badge.svg"></a>
|
||||
<a href="https://badge.fury.io/py/Scrapling" alt="PyPI version">
|
||||
<img alt="PyPI version" src="https://badge.fury.io/py/Scrapling.svg"></a>
|
||||
<a href="https://pepy.tech/project/scrapling" alt="PyPI Downloads">
|
||||
<img alt="PyPI Downloads" src="https://static.pepy.tech/personalized-badge/scrapling?period=total&units=INTERNATIONAL_SYSTEM&left_color=GREY&right_color=GREEN&left_text=Downloads"></a>
|
||||
<br/>
|
||||
<a href="https://discord.gg/EMgGbDceNQ" alt="Discord" target="_blank">
|
||||
<img alt="Discord" src="https://img.shields.io/discord/1360786381042880532?style=social&logo=discord&link=https%3A%2F%2Fdiscord.gg%2FEMgGbDceNQ">
|
||||
</a>
|
||||
<a href="https://x.com/Scrapling_dev" alt="X (formerly Twitter)">
|
||||
<img alt="X (formerly Twitter) Follow" src="https://img.shields.io/twitter/follow/Scrapling_dev?style=social&logo=x&link=https%3A%2F%2Fx.com%2FScrapling_dev">
|
||||
</a>
|
||||
<br/>
|
||||
<a href="https://pypi.org/project/scrapling/" alt="Supported Python versions">
|
||||
<img alt="Supported Python versions" src="https://img.shields.io/pypi/pyversions/scrapling.svg"></a>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<a href="https://scrapling.readthedocs.io/en/latest/parsing/selection/">
|
||||
选择方法
|
||||
</a>
|
||||
·
|
||||
<a href="https://scrapling.readthedocs.io/en/latest/fetching/choosing/">
|
||||
选择获取器
|
||||
</a>
|
||||
·
|
||||
<a href="https://scrapling.readthedocs.io/en/latest/cli/overview/">
|
||||
命令行界面
|
||||
</a>
|
||||
·
|
||||
<a href="https://scrapling.readthedocs.io/en/latest/ai/mcp-server/">
|
||||
MCP模式
|
||||
</a>
|
||||
·
|
||||
<a href="https://scrapling.readthedocs.io/en/latest/tutorials/migrating_from_beautifulsoup/">
|
||||
从Beautifulsoup迁移
|
||||
</a>
|
||||
</p>
|
||||
|
||||
**停止与反机器人系统斗争。停止在每次网站更新后重写选择器。**
|
||||
|
||||
Scrapling不仅仅是另一个网页抓取库。它是第一个**自适应**抓取库,能够从网站变化中学习并与之共同进化。当其他库在网站更新结构时失效,Scrapling会自动重新定位您的元素并保持抓取器运行。
|
||||
|
||||
为现代网络而构建,Scrapling具有**自己的快速解析引擎**和获取器来处理您面临或将要面临的所有网页抓取挑战。由网页抓取者为网页抓取者和普通用户构建,适合每个人。
|
||||
|
||||
```python
|
||||
>> from scrapling.fetchers import Fetcher, AsyncFetcher, StealthyFetcher, DynamicFetcher
|
||||
>> StealthyFetcher.adaptive = True
|
||||
# 隐秘地获取网站源代码!
|
||||
>> page = StealthyFetcher.fetch('https://example.com', headless=True, network_idle=True)
|
||||
>> print(page.status)
|
||||
200
|
||||
>> products = page.css('.product', auto_save=True) # 抓取在网站设计变更后仍能存活的数据!
|
||||
>> # 之后,如果网站结构改变,传递 `adaptive=True`
|
||||
>> products = page.css('.product', adaptive=True) # Scrapling仍然能找到它们!
|
||||
```
|
||||
|
||||
# 赞助商
|
||||
|
||||
<!-- sponsors -->
|
||||
|
||||
<a href="https://www.scrapeless.com/en?utm_source=official&utm_term=scrapling" target="_blank" title="Effortless Web Scraping Toolkit for Business and Developers"><img src="https://raw.githubusercontent.com/D4Vinci/Scrapling/main/images/scrapeless.jpg"></a>
|
||||
<a href="https://evomi.com?utm_source=github&utm_medium=banner&utm_campaign=d4vinci-scrapling" target="_blank" title="Evomi is your Swiss Quality Proxy Provider, starting at $0.49/GB"><img src="https://raw.githubusercontent.com/D4Vinci/Scrapling/main/images/evomi.png"></a>
|
||||
<a href="https://visit.decodo.com/Dy6W0b" target="_blank" title="Try the Most Efficient Residential Proxies for Free"><img src="https://raw.githubusercontent.com/D4Vinci/Scrapling/main/images/decodo.png"></a>
|
||||
<a href="https://petrosky.io/d4vinci" target="_blank" title="PetroSky delivers cutting-edge VPS hosting."><img src="https://raw.githubusercontent.com/D4Vinci/Scrapling/main/images/petrosky.png"></a>
|
||||
<a href="https://app.cyberyozh.com/?utm_source=github&utm_medium=scrapling" target="_blank" title="We have gathered the best solutions for multi‑accounting and automation in one place."><img src="https://raw.githubusercontent.com/D4Vinci/Scrapling/main/images/cyberyozh.png"></a>
|
||||
<a href="https://www.swiftproxy.net/" target="_blank" title="Unlock Reliable Proxy Services with Swiftproxy!"><img src="https://raw.githubusercontent.com/D4Vinci/Scrapling/main/images/swiftproxy.png"></a>
|
||||
<a href="https://www.rapidproxy.io/?ref=d4v" target="_blank" title="Affordable Access to the Proxy World – bypass CAPTCHAs blocks, and avoid additional costs."><img src="https://raw.githubusercontent.com/D4Vinci/Scrapling/main/images/rapidproxy.jpg"></a>
|
||||
<a href="https://serpapi.com/?utm_source=scrapling" target="_blank" title="Scrape Google and other search engines with SerpApi"><img src="https://raw.githubusercontent.com/D4Vinci/Scrapling/main/images/SerpApi.png"></a>
|
||||
|
||||
<!-- /sponsors -->
|
||||
|
||||
<i><sub>想在这里展示您的广告吗?点击[这里](https://github.com/sponsors/D4Vinci)并选择适合您的级别!</sub></i>
|
||||
|
||||
---
|
||||
|
||||
## 主要特性
|
||||
|
||||
### 支持会话的高级网站获取
|
||||
- **HTTP请求**:使用`Fetcher`类进行快速和隐秘的HTTP请求。可以模拟浏览器的TLS指纹、标头并使用HTTP3。
|
||||
- **动态加载**:通过`DynamicFetcher`类使用完整的浏览器自动化获取动态网站,支持Playwright的Chromium、真实Chrome和自定义隐秘模式。
|
||||
- **反机器人绕过**:使用`StealthyFetcher`的高级隐秘功能,使用修改版Firefox和指纹伪装。可以轻松自动绕过所有类型的Cloudflare的Turnstile和Interstitial。
|
||||
- **会话管理**:使用`FetcherSession`、`StealthySession`和`DynamicSession`类持久化会话支持,用于跨请求的cookie和状态管理。
|
||||
- **异步支持**:所有获取器和专用异步会话类的完整异步支持。
|
||||
|
||||
### 自适应抓取和AI集成
|
||||
- 🔄 **智能元素跟踪**:使用智能相似性算法在网站更改后重新定位元素。
|
||||
- 🎯 **智能灵活选择**:CSS选择器、XPath选择器、基于过滤器的搜索、文本搜索、正则表达式搜索等。
|
||||
- 🔍 **查找相似元素**:自动定位与找到的元素相似的元素。
|
||||
- 🤖 **与AI一起使用的MCP服务器**:内置MCP服务器用于AI辅助网页抓取和数据提取。MCP服务器具有自定义的强大功能,利用Scrapling在将内容传递给AI(Claude/Cursor等)之前提取目标内容,从而加快操作并通过最小化令牌使用来降低成本。([演示视频](https://www.youtube.com/watch?v=qyFk3ZNwOxE))
|
||||
|
||||
### 高性能和经过实战测试的架构
|
||||
- 🚀 **闪电般快速**:优化性能超越大多数Python抓取库。
|
||||
- 🔋 **内存高效**:优化的数据结构和延迟加载,最小内存占用。
|
||||
- ⚡ **快速JSON序列化**:比标准库快10倍。
|
||||
- 🏗️ **经过实战测试**:Scrapling不仅拥有92%的测试覆盖率和完整的类型提示覆盖率,而且在过去一年中每天被数百名网页抓取者使用。
|
||||
|
||||
### 对开发者/网页抓取者友好的体验
|
||||
- 🎯 **交互式网页抓取Shell**:可选的内置IPython shell,具有Scrapling集成、快捷方式和新工具,可加快网页抓取脚本开发,例如将curl请求转换为Scrapling请求并在浏览器中查看请求结果。
|
||||
- 🚀 **直接从终端使用**:可选地,您可以使用Scrapling抓取URL而无需编写任何代码!
|
||||
- 🛠️ **丰富的导航API**:使用父级、兄弟级和子级导航方法进行高级DOM遍历。
|
||||
- 🧬 **增强的文本处理**:内置正则表达式、清理方法和优化的字符串操作。
|
||||
- 📝 **自动选择器生成**:为任何元素生成强大的CSS/XPath选择器。
|
||||
- 🔌 **熟悉的API**:类似于Scrapy/BeautifulSoup,使用与Scrapy/Parsel相同的伪元素。
|
||||
- 📘 **完整的类型覆盖**:完整的类型提示,出色的IDE支持和代码补全。
|
||||
- 🔋 **现成的Docker镜像**:每次发布时,包含所有浏览器的Docker镜像会自动构建和推送。
|
||||
|
||||
## 入门
|
||||
|
||||
### 基本用法
|
||||
```python
|
||||
from scrapling.fetchers import Fetcher, StealthyFetcher, DynamicFetcher
|
||||
from scrapling.fetchers import FetcherSession, StealthySession, DynamicSession
|
||||
|
||||
# 支持会话的HTTP请求
|
||||
with FetcherSession(impersonate='chrome') as session: # 使用Chrome的最新版本TLS指纹
|
||||
page = session.get('https://quotes.toscrape.com/', stealthy_headers=True)
|
||||
quotes = page.css('.quote .text::text')
|
||||
|
||||
# 或使用一次性请求
|
||||
page = Fetcher.get('https://quotes.toscrape.com/')
|
||||
quotes = page.css('.quote .text::text')
|
||||
|
||||
# 高级隐秘模式(保持浏览器打开直到完成)
|
||||
with StealthySession(headless=True, solve_cloudflare=True) as session:
|
||||
page = session.fetch('https://nopecha.com/demo/cloudflare', google_search=False)
|
||||
data = page.css('#padded_content a')
|
||||
|
||||
# 或使用一次性请求样式,为此请求打开浏览器,完成后关闭
|
||||
page = StealthyFetcher.fetch('https://nopecha.com/demo/cloudflare')
|
||||
data = page.css('#padded_content a')
|
||||
|
||||
# 完整的浏览器自动化(保持浏览器打开直到完成)
|
||||
with DynamicSession(headless=True) as session:
|
||||
page = session.fetch('https://quotes.toscrape.com/', network_idle=True)
|
||||
quotes = page.css('.quote .text::text')
|
||||
|
||||
# 或使用一次性请求样式
|
||||
page = DynamicFetcher.fetch('https://quotes.toscrape.com/', network_idle=True)
|
||||
quotes = page.css('.quote .text::text')
|
||||
```
|
||||
|
||||
### 元素选择
|
||||
```python
|
||||
# CSS选择器
|
||||
page.css('a::text') # 提取文本
|
||||
page.css('a::attr(href)') # 提取属性
|
||||
page.css('a', recursive=False) # 仅直接元素
|
||||
page.css('a', auto_save=True) # 自动保存元素位置
|
||||
|
||||
# XPath
|
||||
page.xpath('//a/text()')
|
||||
|
||||
# 灵活搜索
|
||||
page.find_by_text('Python', first_match=True) # 按文本查找
|
||||
page.find_by_regex(r'\d{4}') # 按正则表达式模式查找
|
||||
page.find('div', {'class': 'container'}) # 按属性查找
|
||||
|
||||
# 导航
|
||||
element.parent # 获取父元素
|
||||
element.next_sibling # 获取下一个兄弟元素
|
||||
element.children # 获取子元素
|
||||
|
||||
# 相似元素
|
||||
similar = page.get_similar(element) # 查找相似元素
|
||||
|
||||
# 自适应抓取
|
||||
saved_elements = page.css('.product', auto_save=True)
|
||||
# 之后,当网站更改时:
|
||||
page.css('.product', adaptive=True) # 使用保存的位置查找元素
|
||||
```
|
||||
|
||||
### 会话使用
|
||||
```python
|
||||
from scrapling.fetchers import FetcherSession, AsyncFetcherSession
|
||||
|
||||
# 同步会话
|
||||
with FetcherSession() as session:
|
||||
# Cookie自动保持
|
||||
page1 = session.get('https://quotes.toscrape.com/login')
|
||||
page2 = session.post('https://quotes.toscrape.com/login', data={'username': 'admin', 'password': 'admin'})
|
||||
|
||||
# 如需要,切换浏览器指纹
|
||||
page2 = session.get('https://quotes.toscrape.com/', impersonate='firefox135')
|
||||
|
||||
# 异步会话使用
|
||||
async with AsyncStealthySession(max_pages=2) as session:
|
||||
tasks = []
|
||||
urls = ['https://example.com/page1', 'https://example.com/page2']
|
||||
|
||||
for url in urls:
|
||||
task = session.fetch(url)
|
||||
tasks.append(task)
|
||||
|
||||
print(session.get_pool_stats()) # 可选 - 浏览器标签池的状态(忙/空闲/错误)
|
||||
results = await asyncio.gather(*tasks)
|
||||
print(session.get_pool_stats())
|
||||
```
|
||||
|
||||
## CLI和交互式Shell
|
||||
|
||||
Scrapling v0.3包含强大的命令行界面:
|
||||
|
||||
[](https://asciinema.org/a/736339)
|
||||
|
||||
```bash
|
||||
# 启动交互式网页抓取shell
|
||||
scrapling shell
|
||||
|
||||
# 直接将页面提取到文件而无需编程(默认提取`body`标签内的内容)
|
||||
# 如果输出文件以`.txt`结尾,则将提取目标的文本内容。
|
||||
# 如果以`.md`结尾,它将是HTML内容的markdown表示,`.html`将直接是HTML内容。
|
||||
scrapling extract get 'https://example.com' content.md
|
||||
scrapling extract get 'https://example.com' content.txt --css-selector '#fromSkipToProducts' --impersonate 'chrome' # 所有匹配CSS选择器'#fromSkipToProducts'的元素
|
||||
scrapling extract fetch 'https://example.com' content.md --css-selector '#fromSkipToProducts' --no-headless
|
||||
scrapling extract stealthy-fetch 'https://nopecha.com/demo/cloudflare' captchas.html --css-selector '#padded_content a' --solve-cloudflare
|
||||
```
|
||||
|
||||
> [!NOTE]
|
||||
> 还有许多其他功能,但我们希望保持此页面简洁,例如MCP服务器和交互式网页抓取Shell。查看完整文档[这里](https://scrapling.readthedocs.io/en/latest/)
|
||||
|
||||
## 性能基准
|
||||
|
||||
Scrapling不仅功能强大——它还速度极快,自0.3版本以来的更新在所有操作中都提供了卓越的性能改进。
|
||||
|
||||
### 文本提取速度测试(5000个嵌套元素)
|
||||
|
||||
| # | 库 | 时间(ms) | vs Scrapling |
|
||||
|---|:--------------:|:--------:|:------------:|
|
||||
| 1 | Scrapling | 1.92 | 1.0x |
|
||||
| 2 | Parsel/Scrapy | 1.99 | 1.036x |
|
||||
| 3 | Raw Lxml | 2.33 | 1.214x |
|
||||
| 4 | PyQuery | 20.61 | ~11x |
|
||||
| 5 | Selectolax | 80.65 | ~42x |
|
||||
| 6 | BS4 with Lxml | 1283.21 | ~698x |
|
||||
| 7 | MechanicalSoup | 1304.57 | ~679x |
|
||||
| 8 |BS4 with html5lib| 3331.96 | ~1735x |
|
||||
|
||||
### 元素相似性和文本搜索性能
|
||||
|
||||
Scrapling的自适应元素查找功能明显优于替代方案:
|
||||
|
||||
| 库 | 时间(ms) | vs Scrapling |
|
||||
|-------------|:--------:|:------------:|
|
||||
| Scrapling | 1.87 | 1.0x |
|
||||
| AutoScraper | 10.24 | 5.476x |
|
||||
|
||||
|
||||
> 所有基准测试代表100+次运行的平均值。请参阅[benchmarks.py](https://github.com/D4Vinci/Scrapling/blob/main/benchmarks.py)了解方法。
|
||||
|
||||
## 安装
|
||||
|
||||
Scrapling需要Python 3.10或更高版本:
|
||||
|
||||
```bash
|
||||
pip install scrapling
|
||||
```
|
||||
|
||||
从v0.3.2开始,此安装仅包括解析器引擎及其依赖项,没有任何获取器或命令行依赖项。
|
||||
|
||||
### 可选依赖项
|
||||
|
||||
1. 如果您要使用以下任何额外功能、获取器或它们的类,那么您需要安装获取器的依赖项,然后使用以下命令安装它们的浏览器依赖项
|
||||
```bash
|
||||
pip install "scrapling[fetchers]"
|
||||
|
||||
scrapling install
|
||||
```
|
||||
|
||||
这会下载所有浏览器及其系统依赖项和指纹操作依赖项。
|
||||
|
||||
2. 额外功能:
|
||||
- 安装MCP服务器功能:
|
||||
```bash
|
||||
pip install "scrapling[ai]"
|
||||
```
|
||||
- 安装shell功能(网页抓取shell和`extract`命令):
|
||||
```bash
|
||||
pip install "scrapling[shell]"
|
||||
```
|
||||
- 安装所有内容:
|
||||
```bash
|
||||
pip install "scrapling[all]"
|
||||
```
|
||||
请记住,在安装任何这些额外功能后(如果您还没有安装),您需要使用`scrapling install`安装浏览器依赖项
|
||||
|
||||
### Docker
|
||||
您还可以使用以下命令从DockerHub安装包含所有额外功能和浏览器的Docker镜像:
|
||||
```bash
|
||||
docker pull pyd4vinci/scrapling
|
||||
```
|
||||
或从GitHub注册表下载:
|
||||
```bash
|
||||
docker pull ghcr.io/d4vinci/scrapling:latest
|
||||
```
|
||||
此镜像通过仓库主分支上的GitHub actions自动构建和推送。
|
||||
|
||||
## 贡献
|
||||
|
||||
我们欢迎贡献!在开始之前,请阅读我们的[贡献指南](https://github.com/D4Vinci/Scrapling/blob/main/CONTRIBUTING.md)。
|
||||
|
||||
## 免责声明
|
||||
|
||||
> [!CAUTION]
|
||||
> 此库仅用于教育和研究目的。使用此库即表示您同意遵守本地和国际数据抓取和隐私法律。作者和贡献者对本软件的任何滥用不承担责任。始终尊重网站的服务条款和robots.txt文件。
|
||||
|
||||
## 许可证
|
||||
|
||||
本作品根据BSD-3-Clause许可证授权。
|
||||
|
||||
## 致谢
|
||||
|
||||
此项目包含改编自以下内容的代码:
|
||||
- Parsel(BSD许可证)——用于[translator](https://github.com/D4Vinci/Scrapling/blob/main/scrapling/core/translator.py)子模块
|
||||
|
||||
## 感谢和参考
|
||||
|
||||
- [Daijro](https://github.com/daijro)在[BrowserForge](https://github.com/daijro/browserforge)和[Camoufox](https://github.com/daijro/camoufox)上的出色工作
|
||||
- [Vinyzu](https://github.com/Vinyzu)在[Botright](https://github.com/Vinyzu/Botright)和[PatchRight](https://github.com/Kaliiiiiiiiii-Vinyzu/patchright)上的出色工作
|
||||
- [brotector](https://github.com/kaliiiiiiiiii/brotector)提供的浏览器检测绕过技术
|
||||
- [fakebrowser](https://github.com/kkoooqq/fakebrowser)和[BotBrowser](https://github.com/botswin/BotBrowser)提供的指纹识别研究
|
||||
|
||||
---
|
||||
<div align="center"><small>由Karim Shoair用❤️设计和制作。</small></div><br>
|
||||
@@ -0,0 +1,332 @@
|
||||
<p align=center>
|
||||
<br>
|
||||
<a href="https://scrapling.readthedocs.io/en/latest/" target="_blank"><img src="https://raw.githubusercontent.com/D4Vinci/Scrapling/main/images/poster.png" style="width: 50%; height: 100%;" alt="main poster"/></a>
|
||||
<br>
|
||||
<i><code>Einfaches, müheloses Web Scraping, wie es sein sollte!</code></i>
|
||||
</p>
|
||||
<p align="center">
|
||||
<a href="https://github.com/D4Vinci/Scrapling/actions/workflows/tests.yml" alt="Tests">
|
||||
<img alt="Tests" src="https://github.com/D4Vinci/Scrapling/actions/workflows/tests.yml/badge.svg"></a>
|
||||
<a href="https://badge.fury.io/py/Scrapling" alt="PyPI version">
|
||||
<img alt="PyPI version" src="https://badge.fury.io/py/Scrapling.svg"></a>
|
||||
<a href="https://pepy.tech/project/scrapling" alt="PyPI Downloads">
|
||||
<img alt="PyPI Downloads" src="https://static.pepy.tech/personalized-badge/scrapling?period=total&units=INTERNATIONAL_SYSTEM&left_color=GREY&right_color=GREEN&left_text=Downloads"></a>
|
||||
<br/>
|
||||
<a href="https://discord.gg/EMgGbDceNQ" alt="Discord" target="_blank">
|
||||
<img alt="Discord" src="https://img.shields.io/discord/1360786381042880532?style=social&logo=discord&link=https%3A%2F%2Fdiscord.gg%2FEMgGbDceNQ">
|
||||
</a>
|
||||
<a href="https://x.com/Scrapling_dev" alt="X (formerly Twitter)">
|
||||
<img alt="X (formerly Twitter) Follow" src="https://img.shields.io/twitter/follow/Scrapling_dev?style=social&logo=x&link=https%3A%2F%2Fx.com%2FScrapling_dev">
|
||||
</a>
|
||||
<br/>
|
||||
<a href="https://pypi.org/project/scrapling/" alt="Supported Python versions">
|
||||
<img alt="Supported Python versions" src="https://img.shields.io/pypi/pyversions/scrapling.svg"></a>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<a href="https://scrapling.readthedocs.io/en/latest/parsing/selection/">
|
||||
Auswahlmethoden
|
||||
</a>
|
||||
·
|
||||
<a href="https://scrapling.readthedocs.io/en/latest/fetching/choosing/">
|
||||
Fetcher wählen
|
||||
</a>
|
||||
·
|
||||
<a href="https://scrapling.readthedocs.io/en/latest/cli/overview/">
|
||||
CLI
|
||||
</a>
|
||||
·
|
||||
<a href="https://scrapling.readthedocs.io/en/latest/ai/mcp-server/">
|
||||
MCP-Modus
|
||||
</a>
|
||||
·
|
||||
<a href="https://scrapling.readthedocs.io/en/latest/tutorials/migrating_from_beautifulsoup/">
|
||||
Migration von Beautifulsoup
|
||||
</a>
|
||||
</p>
|
||||
|
||||
**Hören Sie auf, gegen Anti-Bot-Systeme zu kämpfen. Hören Sie auf, Selektoren nach jedem Website-Update neu zu schreiben.**
|
||||
|
||||
Scrapling ist nicht nur eine weitere Web-Scraping-Bibliothek. Es ist die erste **adaptive** Scraping-Bibliothek, die von Website-Änderungen lernt und sich mit ihnen weiterentwickelt. Während andere Bibliotheken brechen, wenn Websites ihre Struktur aktualisieren, lokalisiert Scrapling Ihre Elemente automatisch neu und hält Ihre Scraper am Laufen.
|
||||
|
||||
Für das moderne Web entwickelt, bietet Scrapling **seine eigene schnelle Parsing-Engine** und Fetcher, um alle Web-Scraping-Herausforderungen zu bewältigen, denen Sie begegnen oder begegnen werden. Von Web Scrapern für Web Scraper und normale Benutzer entwickelt, ist für jeden etwas dabei.
|
||||
|
||||
```python
|
||||
>> from scrapling.fetchers import Fetcher, AsyncFetcher, StealthyFetcher, DynamicFetcher
|
||||
>> StealthyFetcher.adaptive = True
|
||||
# Holen Sie sich Website-Quellcode unter dem Radar!
|
||||
>> page = StealthyFetcher.fetch('https://example.com', headless=True, network_idle=True)
|
||||
>> print(page.status)
|
||||
200
|
||||
>> products = page.css('.product', auto_save=True) # Scrapen Sie Daten, die Website-Designänderungen überleben!
|
||||
>> # Später, wenn sich die Website-Struktur ändert, übergeben Sie `adaptive=True`
|
||||
>> products = page.css('.product', adaptive=True) # und Scrapling findet sie trotzdem!
|
||||
```
|
||||
|
||||
# Sponsoren
|
||||
|
||||
<!-- sponsors -->
|
||||
|
||||
<a href="https://www.scrapeless.com/en?utm_source=official&utm_term=scrapling" target="_blank" title="Effortless Web Scraping Toolkit for Business and Developers"><img src="https://raw.githubusercontent.com/D4Vinci/Scrapling/main/images/scrapeless.jpg"></a>
|
||||
<a href="https://evomi.com?utm_source=github&utm_medium=banner&utm_campaign=d4vinci-scrapling" target="_blank" title="Evomi is your Swiss Quality Proxy Provider, starting at $0.49/GB"><img src="https://raw.githubusercontent.com/D4Vinci/Scrapling/main/images/evomi.png"></a>
|
||||
<a href="https://visit.decodo.com/Dy6W0b" target="_blank" title="Try the Most Efficient Residential Proxies for Free"><img src="https://raw.githubusercontent.com/D4Vinci/Scrapling/main/images/decodo.png"></a>
|
||||
<a href="https://petrosky.io/d4vinci" target="_blank" title="PetroSky delivers cutting-edge VPS hosting."><img src="https://raw.githubusercontent.com/D4Vinci/Scrapling/main/images/petrosky.png"></a>
|
||||
<a href="https://app.cyberyozh.com/?utm_source=github&utm_medium=scrapling" target="_blank" title="We have gathered the best solutions for multi‑accounting and automation in one place."><img src="https://raw.githubusercontent.com/D4Vinci/Scrapling/main/images/cyberyozh.png"></a>
|
||||
<a href="https://www.swiftproxy.net/" target="_blank" title="Unlock Reliable Proxy Services with Swiftproxy!"><img src="https://raw.githubusercontent.com/D4Vinci/Scrapling/main/images/swiftproxy.png"></a>
|
||||
<a href="https://www.rapidproxy.io/?ref=d4v" target="_blank" title="Affordable Access to the Proxy World – bypass CAPTCHAs blocks, and avoid additional costs."><img src="https://raw.githubusercontent.com/D4Vinci/Scrapling/main/images/rapidproxy.jpg"></a>
|
||||
<a href="https://serpapi.com/?utm_source=scrapling" target="_blank" title="Scrape Google and other search engines with SerpApi"><img src="https://raw.githubusercontent.com/D4Vinci/Scrapling/main/images/SerpApi.png"></a>
|
||||
|
||||
<!-- /sponsors -->
|
||||
|
||||
<i><sub>Möchten Sie Ihre Anzeige hier zeigen? Klicken Sie [hier](https://github.com/sponsors/D4Vinci) und wählen Sie die Stufe, die zu Ihnen passt!</sub></i>
|
||||
|
||||
---
|
||||
|
||||
## Hauptmerkmale
|
||||
|
||||
### Erweiterte Website-Abruf mit Sitzungsunterstützung
|
||||
- **HTTP-Anfragen**: Schnelle und heimliche HTTP-Anfragen mit der `Fetcher`-Klasse. Kann Browser-TLS-Fingerabdrücke, Header imitieren und HTTP3 verwenden.
|
||||
- **Dynamisches Laden**: Abrufen dynamischer Websites mit vollständiger Browser-Automatisierung über die `DynamicFetcher`-Klasse, die Playwrights Chromium, echtes Chrome und benutzerdefinierten Stealth-Modus unterstützt.
|
||||
- **Anti-Bot-Umgehung**: Erweiterte Stealth-Fähigkeiten mit `StealthyFetcher` unter Verwendung einer modifizierten Firefox-Version und Fingerabdruck-Spoofing. Kann alle Arten von Cloudflares Turnstile und Interstitial einfach mit Automatisierung umgehen.
|
||||
- **Sitzungsverwaltung**: Persistente Sitzungsunterstützung mit den Klassen `FetcherSession`, `StealthySession` und `DynamicSession` für Cookie- und Zustandsverwaltung über Anfragen hinweg.
|
||||
- **Async-Unterstützung**: Vollständige Async-Unterstützung über alle Fetcher und dedizierte Async-Sitzungsklassen hinweg.
|
||||
|
||||
### Adaptives Scraping & KI-Integration
|
||||
- 🔄 **Intelligente Element-Verfolgung**: Elemente nach Website-Änderungen mit intelligenten Ähnlichkeitsalgorithmen neu lokalisieren.
|
||||
- 🎯 **Intelligente flexible Auswahl**: CSS-Selektoren, XPath-Selektoren, filterbasierte Suche, Textsuche, Regex-Suche und mehr.
|
||||
- 🔍 **Ähnliche Elemente finden**: Elemente, die gefundenen Elementen ähnlich sind, automatisch lokalisieren.
|
||||
- 🤖 **MCP-Server für die Verwendung mit KI**: Integrierter MCP-Server für KI-unterstütztes Web Scraping und Datenextraktion. Der MCP-Server verfügt über benutzerdefinierte, leistungsstarke Funktionen, die Scrapling nutzen, um gezielten Inhalt zu extrahieren, bevor er an die KI (Claude/Cursor/etc.) übergeben wird, wodurch Vorgänge beschleunigt und Kosten durch Minimierung der Token-Nutzung gesenkt werden. ([Demo-Video](https://www.youtube.com/watch?v=qyFk3ZNwOxE))
|
||||
|
||||
### Hochleistungs- und praxiserprobte Architektur
|
||||
- 🚀 **Blitzschnell**: Optimierte Leistung, die die meisten Python-Scraping-Bibliotheken übertrifft.
|
||||
- 🔋 **Speichereffizient**: Optimierte Datenstrukturen und Lazy Loading für einen minimalen Speicher-Footprint.
|
||||
- ⚡ **Schnelle JSON-Serialisierung**: 10x schneller als die Standardbibliothek.
|
||||
- 🏗️ **Praxiserprobt**: Scrapling hat nicht nur eine Testabdeckung von 92% und eine vollständige Type-Hints-Abdeckung, sondern wird seit dem letzten Jahr täglich von Hunderten von Web Scrapern verwendet.
|
||||
|
||||
### Entwickler/Web-Scraper-freundliche Erfahrung
|
||||
- 🎯 **Interaktive Web-Scraping-Shell**: Optionale integrierte IPython-Shell mit Scrapling-Integration, Shortcuts und neuen Tools zur Beschleunigung der Web-Scraping-Skriptentwicklung, wie das Konvertieren von Curl-Anfragen in Scrapling-Anfragen und das Anzeigen von Anfrageergebnissen in Ihrem Browser.
|
||||
- 🚀 **Direkt vom Terminal aus verwenden**: Optional können Sie Scrapling verwenden, um eine URL zu scrapen, ohne eine einzige Codezeile zu schreiben!
|
||||
- 🛠️ **Umfangreiche Navigations-API**: Erweiterte DOM-Traversierung mit Eltern-, Geschwister- und Kind-Navigationsmethoden.
|
||||
- 🧬 **Verbesserte Textverarbeitung**: Integrierte Regex, Bereinigungsmethoden und optimierte String-Operationen.
|
||||
- 📝 **Automatische Selektorgenerierung**: Robuste CSS/XPath-Selektoren für jedes Element generieren.
|
||||
- 🔌 **Vertraute API**: Ähnlich wie Scrapy/BeautifulSoup mit denselben Pseudo-Elementen, die in Scrapy/Parsel verwendet werden.
|
||||
- 📘 **Vollständige Typabdeckung**: Vollständige Type Hints für hervorragende IDE-Unterstützung und Code-Vervollständigung.
|
||||
- 🔋 **Fertiges Docker-Image**: Mit jeder Veröffentlichung wird automatisch ein Docker-Image erstellt und gepusht, das alle Browser enthält.
|
||||
|
||||
## Erste Schritte
|
||||
|
||||
### Grundlegende Verwendung
|
||||
```python
|
||||
from scrapling.fetchers import Fetcher, StealthyFetcher, DynamicFetcher
|
||||
from scrapling.fetchers import FetcherSession, StealthySession, DynamicSession
|
||||
|
||||
# HTTP-Anfragen mit Sitzungsunterstützung
|
||||
with FetcherSession(impersonate='chrome') as session: # Verwenden Sie die neueste Version von Chromes TLS-Fingerabdruck
|
||||
page = session.get('https://quotes.toscrape.com/', stealthy_headers=True)
|
||||
quotes = page.css('.quote .text::text')
|
||||
|
||||
# Oder verwenden Sie einmalige Anfragen
|
||||
page = Fetcher.get('https://quotes.toscrape.com/')
|
||||
quotes = page.css('.quote .text::text')
|
||||
|
||||
# Erweiterter Stealth-Modus (Browser offen halten, bis Sie fertig sind)
|
||||
with StealthySession(headless=True, solve_cloudflare=True) as session:
|
||||
page = session.fetch('https://nopecha.com/demo/cloudflare', google_search=False)
|
||||
data = page.css('#padded_content a')
|
||||
|
||||
# Oder verwenden Sie den einmaligen Anfragenstil, öffnet den Browser für diese Anfrage und schließt ihn dann nach Abschluss
|
||||
page = StealthyFetcher.fetch('https://nopecha.com/demo/cloudflare')
|
||||
data = page.css('#padded_content a')
|
||||
|
||||
# Vollständige Browser-Automatisierung (Browser offen halten, bis Sie fertig sind)
|
||||
with DynamicSession(headless=True) as session:
|
||||
page = session.fetch('https://quotes.toscrape.com/', network_idle=True)
|
||||
quotes = page.css('.quote .text::text')
|
||||
|
||||
# Oder verwenden Sie den einmaligen Anfragenstil
|
||||
page = DynamicFetcher.fetch('https://quotes.toscrape.com/', network_idle=True)
|
||||
quotes = page.css('.quote .text::text')
|
||||
```
|
||||
|
||||
### Elementauswahl
|
||||
```python
|
||||
# CSS-Selektoren
|
||||
page.css('a::text') # Text extrahieren
|
||||
page.css('a::attr(href)') # Attribute extrahieren
|
||||
page.css('a', recursive=False) # Nur direkte Elemente
|
||||
page.css('a', auto_save=True) # Elementpositionen automatisch speichern
|
||||
|
||||
# XPath
|
||||
page.xpath('//a/text()')
|
||||
|
||||
# Flexible Suche
|
||||
page.find_by_text('Python', first_match=True) # Nach Text suchen
|
||||
page.find_by_regex(r'\d{4}') # Nach Regex-Muster suchen
|
||||
page.find('div', {'class': 'container'}) # Nach Attributen suchen
|
||||
|
||||
# Navigation
|
||||
element.parent # Elternelement abrufen
|
||||
element.next_sibling # Nächstes Geschwister abrufen
|
||||
element.children # Kindelemente abrufen
|
||||
|
||||
# Ähnliche Elemente
|
||||
similar = page.get_similar(element) # Ähnliche Elemente finden
|
||||
|
||||
# Adaptives Scraping
|
||||
saved_elements = page.css('.product', auto_save=True)
|
||||
# Später, wenn sich die Website ändert:
|
||||
page.css('.product', adaptive=True) # Elemente mithilfe gespeicherter Positionen finden
|
||||
```
|
||||
|
||||
### Sitzungsverwendung
|
||||
```python
|
||||
from scrapling.fetchers import FetcherSession, AsyncFetcherSession
|
||||
|
||||
# Synchrone Sitzung
|
||||
with FetcherSession() as session:
|
||||
# Cookies werden automatisch beibehalten
|
||||
page1 = session.get('https://quotes.toscrape.com/login')
|
||||
page2 = session.post('https://quotes.toscrape.com/login', data={'username': 'admin', 'password': 'admin'})
|
||||
|
||||
# Bei Bedarf Browser-Fingerabdruck wechseln
|
||||
page2 = session.get('https://quotes.toscrape.com/', impersonate='firefox135')
|
||||
|
||||
# Async-Sitzungsverwendung
|
||||
async with AsyncStealthySession(max_pages=2) as session:
|
||||
tasks = []
|
||||
urls = ['https://example.com/page1', 'https://example.com/page2']
|
||||
|
||||
for url in urls:
|
||||
task = session.fetch(url)
|
||||
tasks.append(task)
|
||||
|
||||
print(session.get_pool_stats()) # Optional - Der Status des Browser-Tab-Pools (beschäftigt/frei/Fehler)
|
||||
results = await asyncio.gather(*tasks)
|
||||
print(session.get_pool_stats())
|
||||
```
|
||||
|
||||
## CLI & Interaktive Shell
|
||||
|
||||
Scrapling v0.3 enthält eine leistungsstarke Befehlszeilenschnittstelle:
|
||||
|
||||
[](https://asciinema.org/a/736339)
|
||||
|
||||
```bash
|
||||
# Interaktive Web-Scraping-Shell starten
|
||||
scrapling shell
|
||||
|
||||
# Seiten direkt ohne Programmierung in eine Datei extrahieren (Extrahiert standardmäßig den Inhalt im `body`-Tag)
|
||||
# Wenn die Ausgabedatei mit `.txt` endet, wird der Textinhalt des Ziels extrahiert.
|
||||
# Wenn sie mit `.md` endet, ist es eine Markdown-Darstellung des HTML-Inhalts, und `.html` ist direkt der HTML-Inhalt.
|
||||
scrapling extract get 'https://example.com' content.md
|
||||
scrapling extract get 'https://example.com' content.txt --css-selector '#fromSkipToProducts' --impersonate 'chrome' # Alle Elemente, die dem CSS-Selektor '#fromSkipToProducts' entsprechen
|
||||
scrapling extract fetch 'https://example.com' content.md --css-selector '#fromSkipToProducts' --no-headless
|
||||
scrapling extract stealthy-fetch 'https://nopecha.com/demo/cloudflare' captchas.html --css-selector '#padded_content a' --solve-cloudflare
|
||||
```
|
||||
|
||||
> [!NOTE]
|
||||
> Es gibt viele zusätzliche Funktionen, aber wir möchten diese Seite prägnant halten, wie den MCP-Server und die interaktive Web-Scraping-Shell. Schauen Sie sich die vollständige Dokumentation [hier](https://scrapling.readthedocs.io/en/latest/) an
|
||||
|
||||
## Leistungsbenchmarks
|
||||
|
||||
Scrapling ist nicht nur leistungsstark – es ist auch blitzschnell, und die Updates seit Version 0.3 haben außergewöhnliche Leistungsverbesserungen bei allen Operationen gebracht.
|
||||
|
||||
### Textextraktions-Geschwindigkeitstest (5000 verschachtelte Elemente)
|
||||
|
||||
| # | Bibliothek | Zeit (ms) | vs Scrapling |
|
||||
|---|:--------------------:|:---------:|:------------:|
|
||||
| 1 | Scrapling | 1.92 | 1.0x |
|
||||
| 2 | Parsel/Scrapy | 1.99 | 1.036x |
|
||||
| 3 | Raw Lxml | 2.33 | 1.214x |
|
||||
| 4 | PyQuery | 20.61 | ~11x |
|
||||
| 5 | Selectolax | 80.65 | ~42x |
|
||||
| 6 | BS4 mit Lxml | 1283.21 | ~698x |
|
||||
| 7 | MechanicalSoup | 1304.57 | ~679x |
|
||||
| 8 | BS4 mit html5lib | 3331.96 | ~1735x |
|
||||
|
||||
### Element-Ähnlichkeit & Textsuche-Leistung
|
||||
|
||||
Scraplings adaptive Element-Finding-Fähigkeiten übertreffen Alternativen deutlich:
|
||||
|
||||
| Bibliothek | Zeit (ms) | vs Scrapling |
|
||||
|-------------|:---------:|:------------:|
|
||||
| Scrapling | 1.87 | 1.0x |
|
||||
| AutoScraper | 10.24 | 5.476x |
|
||||
|
||||
|
||||
> Alle Benchmarks stellen Durchschnittswerte von über 100 Durchläufen dar. Siehe [benchmarks.py](https://github.com/D4Vinci/Scrapling/blob/main/benchmarks.py) für die Methodik.
|
||||
|
||||
## Installation
|
||||
|
||||
Scrapling erfordert Python 3.10 oder höher:
|
||||
|
||||
```bash
|
||||
pip install scrapling
|
||||
```
|
||||
|
||||
Ab v0.3.2 enthält diese Installation nur die Parser-Engine und ihre Abhängigkeiten, ohne Fetcher oder Kommandozeilenabhängigkeiten.
|
||||
|
||||
### Optionale Abhängigkeiten
|
||||
|
||||
1. Wenn Sie eine der folgenden zusätzlichen Funktionen, die Fetcher oder ihre Klassen verwenden möchten, müssen Sie die Abhängigkeiten der Fetcher installieren und dann ihre Browser-Abhängigkeiten mit
|
||||
```bash
|
||||
pip install "scrapling[fetchers]"
|
||||
|
||||
scrapling install
|
||||
```
|
||||
|
||||
Dies lädt alle Browser mit ihren Systemabhängigkeiten und Fingerabdruck-Manipulationsabhängigkeiten herunter.
|
||||
|
||||
2. Zusätzliche Funktionen:
|
||||
- MCP-Server-Funktion installieren:
|
||||
```bash
|
||||
pip install "scrapling[ai]"
|
||||
```
|
||||
- Shell-Funktionen installieren (Web-Scraping-Shell und der `extract`-Befehl):
|
||||
```bash
|
||||
pip install "scrapling[shell]"
|
||||
```
|
||||
- Alles installieren:
|
||||
```bash
|
||||
pip install "scrapling[all]"
|
||||
```
|
||||
Denken Sie daran, dass Sie nach einem dieser Extras (falls noch nicht geschehen) die Browser-Abhängigkeiten mit `scrapling install` installieren müssen
|
||||
|
||||
### Docker
|
||||
Sie können auch ein Docker-Image mit allen Extras und Browsern mit dem folgenden Befehl von DockerHub installieren:
|
||||
```bash
|
||||
docker pull pyd4vinci/scrapling
|
||||
```
|
||||
Oder laden Sie es aus der GitHub-Registry herunter:
|
||||
```bash
|
||||
docker pull ghcr.io/d4vinci/scrapling:latest
|
||||
```
|
||||
Dieses Image wird automatisch über GitHub Actions im Hauptzweig des Repositorys erstellt und gepusht.
|
||||
|
||||
## Beitragen
|
||||
|
||||
Wir freuen uns über Beiträge! Bitte lesen Sie unsere [Beitragsrichtlinien](https://github.com/D4Vinci/Scrapling/blob/main/CONTRIBUTING.md), bevor Sie beginnen.
|
||||
|
||||
## Haftungsausschluss
|
||||
|
||||
> [!CAUTION]
|
||||
> Diese Bibliothek wird nur zu Bildungs- und Forschungszwecken bereitgestellt. Durch die Nutzung dieser Bibliothek erklären Sie sich damit einverstanden, lokale und internationale Gesetze zum Daten-Scraping und Datenschutz einzuhalten. Die Autoren und Mitwirkenden sind nicht verantwortlich für Missbrauch dieser Software. Respektieren Sie immer die Nutzungsbedingungen von Websites und robots.txt-Dateien.
|
||||
|
||||
## Lizenz
|
||||
|
||||
Diese Arbeit ist unter der BSD-3-Clause-Lizenz lizenziert.
|
||||
|
||||
## Danksagungen
|
||||
|
||||
Dieses Projekt enthält angepassten Code von:
|
||||
- Parsel (BSD-Lizenz) – Verwendet für [translator](https://github.com/D4Vinci/Scrapling/blob/main/scrapling/core/translator.py)-Submodul
|
||||
|
||||
## Dank und Referenzen
|
||||
|
||||
- [Daijros](https://github.com/daijro) brillante Arbeit an [BrowserForge](https://github.com/daijro/browserforge) und [Camoufox](https://github.com/daijro/camoufox)
|
||||
- [Vinyzus](https://github.com/Vinyzu) brillante Arbeit an [Botright](https://github.com/Vinyzu/Botright) und [PatchRight](https://github.com/Kaliiiiiiiiii-Vinyzu/patchright)
|
||||
- [brotector](https://github.com/kaliiiiiiiiii/brotector) für Browser-Erkennungs-Umgehungstechniken
|
||||
- [fakebrowser](https://github.com/kkoooqq/fakebrowser) und [BotBrowser](https://github.com/botswin/BotBrowser) für Fingerprinting-Forschung
|
||||
|
||||
---
|
||||
<div align="center"><small>Entworfen und hergestellt mit ❤️ von Karim Shoair.</small></div><br>
|
||||
@@ -0,0 +1,332 @@
|
||||
<p align=center>
|
||||
<br>
|
||||
<a href="https://scrapling.readthedocs.io/en/latest/" target="_blank"><img src="https://raw.githubusercontent.com/D4Vinci/Scrapling/main/images/poster.png" style="width: 50%; height: 100%;" alt="main poster"/></a>
|
||||
<br>
|
||||
<i><code>¡Web Scraping fácil y sin esfuerzo como debería ser!</code></i>
|
||||
</p>
|
||||
<p align="center">
|
||||
<a href="https://github.com/D4Vinci/Scrapling/actions/workflows/tests.yml" alt="Tests">
|
||||
<img alt="Tests" src="https://github.com/D4Vinci/Scrapling/actions/workflows/tests.yml/badge.svg"></a>
|
||||
<a href="https://badge.fury.io/py/Scrapling" alt="PyPI version">
|
||||
<img alt="PyPI version" src="https://badge.fury.io/py/Scrapling.svg"></a>
|
||||
<a href="https://pepy.tech/project/scrapling" alt="PyPI Downloads">
|
||||
<img alt="PyPI Downloads" src="https://static.pepy.tech/personalized-badge/scrapling?period=total&units=INTERNATIONAL_SYSTEM&left_color=GREY&right_color=GREEN&left_text=Downloads"></a>
|
||||
<br/>
|
||||
<a href="https://discord.gg/EMgGbDceNQ" alt="Discord" target="_blank">
|
||||
<img alt="Discord" src="https://img.shields.io/discord/1360786381042880532?style=social&logo=discord&link=https%3A%2F%2Fdiscord.gg%2FEMgGbDceNQ">
|
||||
</a>
|
||||
<a href="https://x.com/Scrapling_dev" alt="X (formerly Twitter)">
|
||||
<img alt="X (formerly Twitter) Follow" src="https://img.shields.io/twitter/follow/Scrapling_dev?style=social&logo=x&link=https%3A%2F%2Fx.com%2FScrapling_dev">
|
||||
</a>
|
||||
<br/>
|
||||
<a href="https://pypi.org/project/scrapling/" alt="Supported Python versions">
|
||||
<img alt="Supported Python versions" src="https://img.shields.io/pypi/pyversions/scrapling.svg"></a>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<a href="https://scrapling.readthedocs.io/en/latest/parsing/selection/">
|
||||
Métodos de selección
|
||||
</a>
|
||||
·
|
||||
<a href="https://scrapling.readthedocs.io/en/latest/fetching/choosing/">
|
||||
Elegir un fetcher
|
||||
</a>
|
||||
·
|
||||
<a href="https://scrapling.readthedocs.io/en/latest/cli/overview/">
|
||||
CLI
|
||||
</a>
|
||||
·
|
||||
<a href="https://scrapling.readthedocs.io/en/latest/ai/mcp-server/">
|
||||
Modo MCP
|
||||
</a>
|
||||
·
|
||||
<a href="https://scrapling.readthedocs.io/en/latest/tutorials/migrating_from_beautifulsoup/">
|
||||
Migrar desde Beautifulsoup
|
||||
</a>
|
||||
</p>
|
||||
|
||||
**Deja de luchar contra sistemas anti-bot. Deja de reescribir selectores después de cada actualización del sitio web.**
|
||||
|
||||
Scrapling no es solo otra biblioteca de Web Scraping. Es la primera biblioteca de scraping **adaptativa** que aprende de los cambios de los sitios web y evoluciona con ellos. Mientras que otras bibliotecas se rompen cuando los sitios web actualizan su estructura, Scrapling relocaliza automáticamente tus elementos y mantiene tus scrapers funcionando.
|
||||
|
||||
Construido para la Web moderna, Scrapling presenta **su propio motor de análisis rápido** y fetchers para manejar todos los desafíos de Web Scraping que enfrentas o enfrentarás. Construido por Web Scrapers para Web Scrapers y usuarios regulares, hay algo para todos.
|
||||
|
||||
```python
|
||||
>> from scrapling.fetchers import Fetcher, AsyncFetcher, StealthyFetcher, DynamicFetcher
|
||||
>> StealthyFetcher.adaptive = True
|
||||
# ¡Obtén el código fuente de sitios web bajo el radar!
|
||||
>> page = StealthyFetcher.fetch('https://example.com', headless=True, network_idle=True)
|
||||
>> print(page.status)
|
||||
200
|
||||
>> products = page.css('.product', auto_save=True) # ¡Extrae datos que sobreviven a cambios de diseño del sitio web!
|
||||
>> # Más tarde, si la estructura del sitio web cambia, pasa `adaptive=True`
|
||||
>> products = page.css('.product', adaptive=True) # ¡y Scrapling aún los encuentra!
|
||||
```
|
||||
|
||||
# Patrocinadores
|
||||
|
||||
<!-- sponsors -->
|
||||
|
||||
<a href="https://www.scrapeless.com/en?utm_source=official&utm_term=scrapling" target="_blank" title="Effortless Web Scraping Toolkit for Business and Developers"><img src="https://raw.githubusercontent.com/D4Vinci/Scrapling/main/images/scrapeless.jpg"></a>
|
||||
<a href="https://evomi.com?utm_source=github&utm_medium=banner&utm_campaign=d4vinci-scrapling" target="_blank" title="Evomi is your Swiss Quality Proxy Provider, starting at $0.49/GB"><img src="https://raw.githubusercontent.com/D4Vinci/Scrapling/main/images/evomi.png"></a>
|
||||
<a href="https://visit.decodo.com/Dy6W0b" target="_blank" title="Try the Most Efficient Residential Proxies for Free"><img src="https://raw.githubusercontent.com/D4Vinci/Scrapling/main/images/decodo.png"></a>
|
||||
<a href="https://petrosky.io/d4vinci" target="_blank" title="PetroSky delivers cutting-edge VPS hosting."><img src="https://raw.githubusercontent.com/D4Vinci/Scrapling/main/images/petrosky.png"></a>
|
||||
<a href="https://app.cyberyozh.com/?utm_source=github&utm_medium=scrapling" target="_blank" title="We have gathered the best solutions for multi‑accounting and automation in one place."><img src="https://raw.githubusercontent.com/D4Vinci/Scrapling/main/images/cyberyozh.png"></a>
|
||||
<a href="https://www.swiftproxy.net/" target="_blank" title="Unlock Reliable Proxy Services with Swiftproxy!"><img src="https://raw.githubusercontent.com/D4Vinci/Scrapling/main/images/swiftproxy.png"></a>
|
||||
<a href="https://www.rapidproxy.io/?ref=d4v" target="_blank" title="Affordable Access to the Proxy World – bypass CAPTCHAs blocks, and avoid additional costs."><img src="https://raw.githubusercontent.com/D4Vinci/Scrapling/main/images/rapidproxy.jpg"></a>
|
||||
<a href="https://serpapi.com/?utm_source=scrapling" target="_blank" title="Scrape Google and other search engines with SerpApi"><img src="https://raw.githubusercontent.com/D4Vinci/Scrapling/main/images/SerpApi.png"></a>
|
||||
|
||||
<!-- /sponsors -->
|
||||
|
||||
<i><sub>¿Quieres mostrar tu anuncio aquí? ¡Haz clic [aquí](https://github.com/sponsors/D4Vinci) y elige el nivel que te convenga!</sub></i>
|
||||
|
||||
---
|
||||
|
||||
## Características Principales
|
||||
|
||||
### Obtención Avanzada de Sitios Web con Soporte de Sesión
|
||||
- **Solicitudes HTTP**: Solicitudes HTTP rápidas y sigilosas con la clase `Fetcher`. Puede imitar la huella TLS de los navegadores, encabezados y usar HTTP3.
|
||||
- **Carga Dinámica**: Obtén sitios web dinámicos con automatización completa del navegador a través de la clase `DynamicFetcher` compatible con Chromium de Playwright, Chrome real y modo sigiloso personalizado.
|
||||
- **Evasión Anti-bot**: Capacidades de sigilo avanzadas con `StealthyFetcher` usando una versión modificada de Firefox y falsificación de huellas digitales. Puede evadir todos los tipos de Turnstile e Interstitial de Cloudflare con automatización fácilmente.
|
||||
- **Gestión de Sesión**: Soporte de sesión persistente con las clases `FetcherSession`, `StealthySession` y `DynamicSession` para la gestión de cookies y estado entre solicitudes.
|
||||
- **Soporte Async**: Soporte async completo en todos los fetchers y clases de sesión async dedicadas.
|
||||
|
||||
### Scraping Adaptativo e Integración con IA
|
||||
- 🔄 **Seguimiento Inteligente de Elementos**: Relocaliza elementos después de cambios en el sitio web usando algoritmos inteligentes de similitud.
|
||||
- 🎯 **Selección Flexible Inteligente**: Selectores CSS, selectores XPath, búsqueda basada en filtros, búsqueda de texto, búsqueda regex y más.
|
||||
- 🔍 **Encontrar Elementos Similares**: Localiza automáticamente elementos similares a los elementos encontrados.
|
||||
- 🤖 **Servidor MCP para usar con IA**: Servidor MCP integrado para Web Scraping asistido por IA y extracción de datos. El servidor MCP presenta capacidades personalizadas y poderosas que utilizan Scrapling para extraer contenido específico antes de pasarlo a la IA (Claude/Cursor/etc), acelerando así las operaciones y reduciendo costos al minimizar el uso de tokens. ([video demo](https://www.youtube.com/watch?v=qyFk3ZNwOxE))
|
||||
|
||||
### Arquitectura de Alto Rendimiento y Probada en Batalla
|
||||
- 🚀 **Ultrarrápido**: Rendimiento optimizado que supera a la mayoría de las bibliotecas de scraping de Python.
|
||||
- 🔋 **Eficiente en Memoria**: Estructuras de datos optimizadas y carga diferida para una huella de memoria mínima.
|
||||
- ⚡ **Serialización JSON Rápida**: 10 veces más rápido que la biblioteca estándar.
|
||||
- 🏗️ **Probado en batalla**: Scrapling no solo tiene una cobertura de prueba del 92% y cobertura completa de type hints, sino que ha sido utilizado diariamente por cientos de Web Scrapers durante el último año.
|
||||
|
||||
### Experiencia Amigable para Desarrolladores/Web Scrapers
|
||||
- 🎯 **Shell Interactivo de Web Scraping**: Shell IPython integrado opcional con integración de Scrapling, atajos y nuevas herramientas para acelerar el desarrollo de scripts de Web Scraping, como convertir solicitudes curl a solicitudes Scrapling y ver resultados de solicitudes en tu navegador.
|
||||
- 🚀 **Úsalo directamente desde la Terminal**: Opcionalmente, ¡puedes usar Scrapling para hacer scraping de una URL sin escribir ni una sola línea de código!
|
||||
- 🛠️ **API de Navegación Rica**: Recorrido avanzado del DOM con métodos de navegación de padres, hermanos e hijos.
|
||||
- 🧬 **Procesamiento de Texto Mejorado**: Métodos integrados de regex, limpieza y operaciones de cadena optimizadas.
|
||||
- 📝 **Generación Automática de Selectores**: Genera selectores CSS/XPath robustos para cualquier elemento.
|
||||
- 🔌 **API Familiar**: Similar a Scrapy/BeautifulSoup con los mismos pseudo-elementos usados en Scrapy/Parsel.
|
||||
- 📘 **Cobertura Completa de Tipos**: Type hints completos para excelente soporte de IDE y autocompletado de código.
|
||||
- 🔋 **Imagen Docker Lista**: Con cada lanzamiento, se construye y publica automáticamente una imagen Docker que contiene todos los navegadores.
|
||||
|
||||
## Empezando
|
||||
|
||||
### Uso Básico
|
||||
```python
|
||||
from scrapling.fetchers import Fetcher, StealthyFetcher, DynamicFetcher
|
||||
from scrapling.fetchers import FetcherSession, StealthySession, DynamicSession
|
||||
|
||||
# Solicitudes HTTP con soporte de sesión
|
||||
with FetcherSession(impersonate='chrome') as session: # Usa la última versión de la huella TLS de Chrome
|
||||
page = session.get('https://quotes.toscrape.com/', stealthy_headers=True)
|
||||
quotes = page.css('.quote .text::text')
|
||||
|
||||
# O usa solicitudes de una sola vez
|
||||
page = Fetcher.get('https://quotes.toscrape.com/')
|
||||
quotes = page.css('.quote .text::text')
|
||||
|
||||
# Modo sigiloso avanzado (Mantén el navegador abierto hasta que termines)
|
||||
with StealthySession(headless=True, solve_cloudflare=True) as session:
|
||||
page = session.fetch('https://nopecha.com/demo/cloudflare', google_search=False)
|
||||
data = page.css('#padded_content a')
|
||||
|
||||
# O usa el estilo de solicitud de una sola vez, abre el navegador para esta solicitud, luego lo cierra después de terminar
|
||||
page = StealthyFetcher.fetch('https://nopecha.com/demo/cloudflare')
|
||||
data = page.css('#padded_content a')
|
||||
|
||||
# Automatización completa del navegador (Mantén el navegador abierto hasta que termines)
|
||||
with DynamicSession(headless=True) as session:
|
||||
page = session.fetch('https://quotes.toscrape.com/', network_idle=True)
|
||||
quotes = page.css('.quote .text::text')
|
||||
|
||||
# O usa el estilo de solicitud de una sola vez
|
||||
page = DynamicFetcher.fetch('https://quotes.toscrape.com/', network_idle=True)
|
||||
quotes = page.css('.quote .text::text')
|
||||
```
|
||||
|
||||
### Selección de Elementos
|
||||
```python
|
||||
# CSS selectors
|
||||
page.css('a::text') # Extracta texto
|
||||
page.css('a::attr(href)') # Extracta atributos
|
||||
page.css('a', recursive=False) # Solo elementos directos
|
||||
page.css('a', auto_save=True) # Guarda posiciones de los elementos automáticamente
|
||||
|
||||
# XPath
|
||||
page.xpath('//a/text()')
|
||||
|
||||
# Búsqueda flexible
|
||||
page.find_by_text('Python', first_match=True) # Encuentra por texto
|
||||
page.find_by_regex(r'\d{4}') # Encuentra por patrón regex
|
||||
page.find('div', {'class': 'container'}) # Encuentra por atributos
|
||||
|
||||
# Navegación
|
||||
element.parent # Obtener elemento padre
|
||||
element.next_sibling # Obtener siguiente hermano
|
||||
element.children # Obtener hijos
|
||||
|
||||
# Elementos similares
|
||||
similar = page.get_similar(element) # Encuentra elementos similares
|
||||
|
||||
# Scraping adaptativo
|
||||
saved_elements = page.css('.product', auto_save=True)
|
||||
# Más tarde, cuando el sitio web cambia:
|
||||
page.css('.product', adaptive=True) # Encuentra elementos usando posiciones guardadas
|
||||
```
|
||||
|
||||
### Uso de Sesión
|
||||
```python
|
||||
from scrapling.fetchers import FetcherSession, AsyncFetcherSession
|
||||
|
||||
# Sesión sincrónica
|
||||
with FetcherSession() as session:
|
||||
# Las cookies se mantienen automáticamente
|
||||
page1 = session.get('https://quotes.toscrape.com/login')
|
||||
page2 = session.post('https://quotes.toscrape.com/login', data={'username': 'admin', 'password': 'admin'})
|
||||
|
||||
# Cambiar fingerprint del navegador si es necesario
|
||||
page2 = session.get('https://quotes.toscrape.com/', impersonate='firefox135')
|
||||
|
||||
# Uso de sesión async
|
||||
async with AsyncStealthySession(max_pages=2) as session:
|
||||
tasks = []
|
||||
urls = ['https://example.com/page1', 'https://example.com/page2']
|
||||
|
||||
for url in urls:
|
||||
task = session.fetch(url)
|
||||
tasks.append(task)
|
||||
|
||||
print(session.get_pool_stats()) # Opcional - El estado del pool de pestañas del navegador (ocupado/libre/error)
|
||||
results = await asyncio.gather(*tasks)
|
||||
print(session.get_pool_stats())
|
||||
```
|
||||
|
||||
## CLI y Shell Interactivo
|
||||
|
||||
Scrapling v0.3 incluye una poderosa interfaz de línea de comandos:
|
||||
|
||||
[](https://asciinema.org/a/736339)
|
||||
|
||||
```bash
|
||||
# Lanzar shell interactivo de Web Scraping
|
||||
scrapling shell
|
||||
|
||||
# Extraer páginas a un archivo directamente sin programar (Extrae el contenido dentro de la etiqueta `body` por defecto)
|
||||
# Si el archivo de salida termina con `.txt`, entonces se extraerá el contenido de texto del objetivo.
|
||||
# Si termina con `.md`, será una representación markdown del contenido HTML, y `.html` será el contenido HTML directamente.
|
||||
scrapling extract get 'https://example.com' content.md
|
||||
scrapling extract get 'https://example.com' content.txt --css-selector '#fromSkipToProducts' --impersonate 'chrome' # Todos los elementos que coinciden con el selector CSS '#fromSkipToProducts'
|
||||
scrapling extract fetch 'https://example.com' content.md --css-selector '#fromSkipToProducts' --no-headless
|
||||
scrapling extract stealthy-fetch 'https://nopecha.com/demo/cloudflare' captchas.html --css-selector '#padded_content a' --solve-cloudflare
|
||||
```
|
||||
|
||||
> [!NOTE]
|
||||
> Hay muchas características adicionales, pero queremos mantener esta página concisa, como el servidor MCP y el Shell Interactivo de Web Scraping. Consulta la documentación completa [aquí](https://scrapling.readthedocs.io/en/latest/)
|
||||
|
||||
## Benchmarks de Rendimiento
|
||||
|
||||
Scrapling no solo es poderoso, también es increíblemente rápido, y las actualizaciones desde la versión 0.3 han brindado mejoras de rendimiento excepcionales en todas las operaciones.
|
||||
|
||||
### Prueba de Velocidad de Extracción de Texto (5000 elementos anidados)
|
||||
|
||||
| # | Biblioteca | Tiempo (ms) | vs Scrapling |
|
||||
|---|:--------------------:|:-----------:|:------------:|
|
||||
| 1 | Scrapling | 1.92 | 1.0x |
|
||||
| 2 | Parsel/Scrapy | 1.99 | 1.036x |
|
||||
| 3 | Raw Lxml | 2.33 | 1.214x |
|
||||
| 4 | PyQuery | 20.61 | ~11x |
|
||||
| 5 | Selectolax | 80.65 | ~42x |
|
||||
| 6 | BS4 con Lxml | 1283.21 | ~698x |
|
||||
| 7 | MechanicalSoup | 1304.57 | ~679x |
|
||||
| 8 | BS4 con html5lib | 3331.96 | ~1735x |
|
||||
|
||||
### Rendimiento de Similitud de Elementos y Búsqueda de Texto
|
||||
|
||||
Las capacidades de búsqueda adaptativa de elementos de Scrapling superan significativamente a las alternativas:
|
||||
|
||||
| Biblioteca | Tiempo (ms) | vs Scrapling |
|
||||
|--------------|:-----------:|:------------:|
|
||||
| Scrapling | 1.87 | 1.0x |
|
||||
| AutoScraper | 10.24 | 5.476x |
|
||||
|
||||
|
||||
> Todos los benchmarks representan promedios de más de 100 ejecuciones. Ver [benchmarks.py](https://github.com/D4Vinci/Scrapling/blob/main/benchmarks.py) para la metodología.
|
||||
|
||||
## Instalación
|
||||
|
||||
Scrapling requiere Python 3.10 o superior:
|
||||
|
||||
```bash
|
||||
pip install scrapling
|
||||
```
|
||||
|
||||
A partir de v0.3.2, esta instalación solo incluye el motor de análisis y sus dependencias, sin ningún fetcher o dependencias de línea de comandos.
|
||||
|
||||
### Dependencias Opcionales
|
||||
|
||||
1. Si vas a usar alguna de las características adicionales a continuación, los fetchers, o sus clases, entonces necesitas instalar las dependencias de los fetchers y luego instalar sus dependencias del navegador con
|
||||
```bash
|
||||
pip install "scrapling[fetchers]"
|
||||
|
||||
scrapling install
|
||||
```
|
||||
|
||||
Esto descarga todos los navegadores con sus dependencias del sistema y dependencias de manipulación de huellas digitales.
|
||||
|
||||
2. Características adicionales:
|
||||
- Instalar la característica del servidor MCP:
|
||||
```bash
|
||||
pip install "scrapling[ai]"
|
||||
```
|
||||
- Instalar características del shell (shell de Web Scraping y el comando `extract`):
|
||||
```bash
|
||||
pip install "scrapling[shell]"
|
||||
```
|
||||
- Instalar todo:
|
||||
```bash
|
||||
pip install "scrapling[all]"
|
||||
```
|
||||
Recuerda que necesitas instalar las dependencias del navegador con `scrapling install` después de cualquiera de estos extras (si no lo hiciste ya)
|
||||
|
||||
### Docker
|
||||
También puedes instalar una imagen Docker con todos los extras y navegadores con el siguiente comando desde DockerHub:
|
||||
```bash
|
||||
docker pull pyd4vinci/scrapling
|
||||
```
|
||||
O descárgala desde el registro de GitHub:
|
||||
```bash
|
||||
docker pull ghcr.io/d4vinci/scrapling:latest
|
||||
```
|
||||
Esta imagen se construye y publica automáticamente a través de GitHub actions en la rama principal del repositorio.
|
||||
|
||||
## Contribuir
|
||||
|
||||
¡Damos la bienvenida a las contribuciones! Por favor lee nuestras [pautas de contribución](https://github.com/D4Vinci/Scrapling/blob/main/CONTRIBUTING.md) antes de comenzar.
|
||||
|
||||
## Descargo de Responsabilidad
|
||||
|
||||
> [!CAUTION]
|
||||
> Esta biblioteca se proporciona solo con fines educativos y de investigación. Al usar esta biblioteca, aceptas cumplir con las leyes locales e internacionales de scraping de datos y privacidad. Los autores y contribuyentes no son responsables de ningún mal uso de este software. Respeta siempre los términos de servicio de los sitios web y los archivos robots.txt.
|
||||
|
||||
## Licencia
|
||||
|
||||
Este trabajo está licenciado bajo la Licencia BSD-3-Clause.
|
||||
|
||||
## Agradecimientos
|
||||
|
||||
Este proyecto incluye código adaptado de:
|
||||
- Parsel (Licencia BSD)—Usado para el submódulo [translator](https://github.com/D4Vinci/Scrapling/blob/main/scrapling/core/translator.py)
|
||||
|
||||
## Agradecimientos y Referencias
|
||||
|
||||
- El brillante trabajo de [Daijro](https://github.com/daijro) en [BrowserForge](https://github.com/daijro/browserforge) y [Camoufox](https://github.com/daijro/camoufox)
|
||||
- El brillante trabajo de [Vinyzu](https://github.com/Vinyzu) en [Botright](https://github.com/Vinyzu/Botright) y [PatchRight](https://github.com/Kaliiiiiiiiii-Vinyzu/patchright)
|
||||
- [brotector](https://github.com/kaliiiiiiiiii/brotector) por técnicas de evasión de detección de navegador
|
||||
- [fakebrowser](https://github.com/kkoooqq/fakebrowser) y [BotBrowser](https://github.com/botswin/BotBrowser) por investigación de huellas digitales
|
||||
|
||||
---
|
||||
<div align="center"><small>Diseñado y elaborado con ❤️ por Karim Shoair.</small></div><br>
|
||||
@@ -0,0 +1,332 @@
|
||||
<p align=center>
|
||||
<br>
|
||||
<a href="https://scrapling.readthedocs.io/en/latest/" target="_blank"><img src="https://raw.githubusercontent.com/D4Vinci/Scrapling/main/images/poster.png" style="width: 50%; height: 100%;" alt="main poster"/></a>
|
||||
<br>
|
||||
<i><code>簡単で効率的なウェブスクレイピング、あるべき姿!</code></i>
|
||||
</p>
|
||||
<p align="center">
|
||||
<a href="https://github.com/D4Vinci/Scrapling/actions/workflows/tests.yml" alt="Tests">
|
||||
<img alt="Tests" src="https://github.com/D4Vinci/Scrapling/actions/workflows/tests.yml/badge.svg"></a>
|
||||
<a href="https://badge.fury.io/py/Scrapling" alt="PyPI version">
|
||||
<img alt="PyPI version" src="https://badge.fury.io/py/Scrapling.svg"></a>
|
||||
<a href="https://pepy.tech/project/scrapling" alt="PyPI Downloads">
|
||||
<img alt="PyPI Downloads" src="https://static.pepy.tech/personalized-badge/scrapling?period=total&units=INTERNATIONAL_SYSTEM&left_color=GREY&right_color=GREEN&left_text=Downloads"></a>
|
||||
<br/>
|
||||
<a href="https://discord.gg/EMgGbDceNQ" alt="Discord" target="_blank">
|
||||
<img alt="Discord" src="https://img.shields.io/discord/1360786381042880532?style=social&logo=discord&link=https%3A%2F%2Fdiscord.gg%2FEMgGbDceNQ">
|
||||
</a>
|
||||
<a href="https://x.com/Scrapling_dev" alt="X (formerly Twitter)">
|
||||
<img alt="X (formerly Twitter) Follow" src="https://img.shields.io/twitter/follow/Scrapling_dev?style=social&logo=x&link=https%3A%2F%2Fx.com%2FScrapling_dev">
|
||||
</a>
|
||||
<br/>
|
||||
<a href="https://pypi.org/project/scrapling/" alt="Supported Python versions">
|
||||
<img alt="Supported Python versions" src="https://img.shields.io/pypi/pyversions/scrapling.svg"></a>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<a href="https://scrapling.readthedocs.io/en/latest/parsing/selection/">
|
||||
選択メソッド
|
||||
</a>
|
||||
·
|
||||
<a href="https://scrapling.readthedocs.io/en/latest/fetching/choosing/">
|
||||
フェッチャーの選択
|
||||
</a>
|
||||
·
|
||||
<a href="https://scrapling.readthedocs.io/en/latest/cli/overview/">
|
||||
CLI
|
||||
</a>
|
||||
·
|
||||
<a href="https://scrapling.readthedocs.io/en/latest/ai/mcp-server/">
|
||||
MCPモード
|
||||
</a>
|
||||
·
|
||||
<a href="https://scrapling.readthedocs.io/en/latest/tutorials/migrating_from_beautifulsoup/">
|
||||
Beautifulsoupからの移行
|
||||
</a>
|
||||
</p>
|
||||
|
||||
**アンチボットシステムとの戦いをやめましょう。ウェブサイトが更新されるたびにセレクタを書き直すのをやめましょう。**
|
||||
|
||||
Scraplingは単なるウェブスクレイピングライブラリではありません。ウェブサイトの変更から学習し、それとともに進化する最初の**適応型**スクレイピングライブラリです。他のライブラリがウェブサイトの構造が更新されると壊れる一方で、Scraplingは自動的に要素を再配置し、スクレイパーを稼働し続けます。
|
||||
|
||||
モダンウェブ向けに構築されたScraplingは、**独自の高速パースエンジン**とフェッチャーを備えており、あなたが直面する、または直面するであろうすべてのウェブスクレイピングの課題に対応します。ウェブスクレイパーによってウェブスクレイパーと一般ユーザーのために構築され、誰にでも何かがあります。
|
||||
|
||||
```python
|
||||
>> from scrapling.fetchers import Fetcher, AsyncFetcher, StealthyFetcher, DynamicFetcher
|
||||
>> StealthyFetcher.adaptive = True
|
||||
# レーダーの下でウェブサイトのソースを取得!
|
||||
>> page = StealthyFetcher.fetch('https://example.com', headless=True, network_idle=True)
|
||||
>> print(page.status)
|
||||
200
|
||||
>> products = page.css('.product', auto_save=True) # ウェブサイトのデザイン変更に耐えるデータをスクレイプ!
|
||||
>> # 後でウェブサイトの構造が変わったら、`adaptive=True`を渡す
|
||||
>> products = page.css('.product', adaptive=True) # そしてScraplingはまだそれらを見つけます!
|
||||
```
|
||||
|
||||
# スポンサー
|
||||
|
||||
<!-- sponsors -->
|
||||
|
||||
<a href="https://www.scrapeless.com/en?utm_source=official&utm_term=scrapling" target="_blank" title="Effortless Web Scraping Toolkit for Business and Developers"><img src="https://raw.githubusercontent.com/D4Vinci/Scrapling/main/images/scrapeless.jpg"></a>
|
||||
<a href="https://evomi.com?utm_source=github&utm_medium=banner&utm_campaign=d4vinci-scrapling" target="_blank" title="Evomi is your Swiss Quality Proxy Provider, starting at $0.49/GB"><img src="https://raw.githubusercontent.com/D4Vinci/Scrapling/main/images/evomi.png"></a>
|
||||
<a href="https://visit.decodo.com/Dy6W0b" target="_blank" title="Try the Most Efficient Residential Proxies for Free"><img src="https://raw.githubusercontent.com/D4Vinci/Scrapling/main/images/decodo.png"></a>
|
||||
<a href="https://petrosky.io/d4vinci" target="_blank" title="PetroSky delivers cutting-edge VPS hosting."><img src="https://raw.githubusercontent.com/D4Vinci/Scrapling/main/images/petrosky.png"></a>
|
||||
<a href="https://app.cyberyozh.com/?utm_source=github&utm_medium=scrapling" target="_blank" title="We have gathered the best solutions for multi‑accounting and automation in one place."><img src="https://raw.githubusercontent.com/D4Vinci/Scrapling/main/images/cyberyozh.png"></a>
|
||||
<a href="https://www.swiftproxy.net/" target="_blank" title="Unlock Reliable Proxy Services with Swiftproxy!"><img src="https://raw.githubusercontent.com/D4Vinci/Scrapling/main/images/swiftproxy.png"></a>
|
||||
<a href="https://www.rapidproxy.io/?ref=d4v" target="_blank" title="Affordable Access to the Proxy World – bypass CAPTCHAs blocks, and avoid additional costs."><img src="https://raw.githubusercontent.com/D4Vinci/Scrapling/main/images/rapidproxy.jpg"></a>
|
||||
<a href="https://serpapi.com/?utm_source=scrapling" target="_blank" title="Scrape Google and other search engines with SerpApi"><img src="https://raw.githubusercontent.com/D4Vinci/Scrapling/main/images/SerpApi.png"></a>
|
||||
|
||||
<!-- /sponsors -->
|
||||
|
||||
<i><sub>ここに広告を表示したいですか?[こちら](https://github.com/sponsors/D4Vinci)をクリックして、あなたに合ったティアを選択してください!</sub></i>
|
||||
|
||||
---
|
||||
|
||||
## 主な機能
|
||||
|
||||
### セッションサポート付き高度なウェブサイト取得
|
||||
- **HTTPリクエスト**:`Fetcher`クラスで高速でステルスなHTTPリクエスト。ブラウザのTLSフィンガープリント、ヘッダーを模倣し、HTTP3を使用できます。
|
||||
- **動的読み込み**:Playwright's Chromium、実際のChrome、カスタムステルスモードをサポートする`DynamicFetcher`クラスを通じた完全なブラウザ自動化で動的ウェブサイトを取得。
|
||||
- **アンチボット回避**:修正されたFirefoxとフィンガープリント偽装を使用した`StealthyFetcher`による高度なステルス機能。自動化でCloudflareのTurnstileとInterstitialのすべてのタイプを簡単に回避できます。
|
||||
- **セッション管理**:リクエスト間でCookieと状態を管理するための`FetcherSession`、`StealthySession`、`DynamicSession`クラスによる永続的なセッションサポート。
|
||||
- **非同期サポート**:すべてのフェッチャーと専用非同期セッションクラス全体での完全な非同期サポート。
|
||||
|
||||
### 適応型スクレイピングとAI統合
|
||||
- 🔄 **スマート要素追跡**:インテリジェントな類似性アルゴリズムを使用してウェブサイトの変更後に要素を再配置。
|
||||
- 🎯 **スマート柔軟選択**:CSSセレクタ、XPathセレクタ、フィルタベース検索、テキスト検索、正規表現検索など。
|
||||
- 🔍 **類似要素を見つける**:見つかった要素に類似した要素を自動的に特定。
|
||||
- 🤖 **AIと使用するMCPサーバー**:AI支援ウェブスクレイピングとデータ抽出のための組み込みMCPサーバー。MCPサーバーは、AI(Claude/Cursorなど)に渡す前にScraplingを利用してターゲットコンテンツを抽出するカスタムで強力な機能を備えており、操作を高速化し、トークン使用量を最小限に抑えることでコストを削減します。([デモビデオ](https://www.youtube.com/watch?v=qyFk3ZNwOxE))
|
||||
|
||||
### 高性能で実戦テスト済みのアーキテクチャ
|
||||
- 🚀 **高速**:ほとんどのPythonスクレイピングライブラリを上回る最適化されたパフォーマンス。
|
||||
- 🔋 **メモリ効率**:最小のメモリフットプリントのための最適化されたデータ構造と遅延読み込み。
|
||||
- ⚡ **高速JSONシリアル化**:標準ライブラリの10倍の速度。
|
||||
- 🏗️ **実戦テスト済み**:Scraplingは92%のテストカバレッジと完全な型ヒントカバレッジを備えているだけでなく、過去1年間に数百人のウェブスクレイパーによって毎日使用されてきました。
|
||||
|
||||
### 開発者/ウェブスクレイパーにやさしい体験
|
||||
- 🎯 **インタラクティブウェブスクレイピングシェル**:Scraping統合、ショートカット、curlリクエストをScraplingリクエストに変換したり、ブラウザでリクエスト結果を表示したりするなどの新しいツールを備えたオプションの組み込みIPythonシェルで、ウェブスクレイピングスクリプトの開発を加速します。
|
||||
- 🚀 **ターミナルから直接使用**:オプションで、コードを一行も書かずにScraplingを使用してURLをスクレイプできます!
|
||||
- 🛠️ **豊富なナビゲーションAPI**:親、兄弟、子のナビゲーションメソッドによる高度なDOMトラバーサル。
|
||||
- 🧬 **強化されたテキスト処理**:組み込みの正規表現、クリーニングメソッド、最適化された文字列操作。
|
||||
- 📝 **自動セレクタ生成**:任意の要素に対して堅牢なCSS/XPathセレクタを生成。
|
||||
- 🔌 **馴染みのあるAPI**:Scrapy/Parselで使用されている同じ疑似要素を持つScrapy/BeautifulSoupに似ています。
|
||||
- 📘 **完全な型カバレッジ**:優れたIDEサポートとコード補完のための完全な型ヒント。
|
||||
- 🔋 **すぐに使えるDockerイメージ**:各リリースで、すべてのブラウザを含むDockerイメージが自動的にビルドおよびプッシュされます。
|
||||
|
||||
## はじめに
|
||||
|
||||
### 基本的な使い方
|
||||
```python
|
||||
from scrapling.fetchers import Fetcher, StealthyFetcher, DynamicFetcher
|
||||
from scrapling.fetchers import FetcherSession, StealthySession, DynamicSession
|
||||
|
||||
# セッションサポート付きHTTPリクエスト
|
||||
with FetcherSession(impersonate='chrome') as session: # ChromeのTLSフィンガープリントの最新バージョンを使用
|
||||
page = session.get('https://quotes.toscrape.com/', stealthy_headers=True)
|
||||
quotes = page.css('.quote .text::text')
|
||||
|
||||
# または一回限りのリクエストを使用
|
||||
page = Fetcher.get('https://quotes.toscrape.com/')
|
||||
quotes = page.css('.quote .text::text')
|
||||
|
||||
# 高度なステルスモード(完了するまでブラウザを開いたままにする)
|
||||
with StealthySession(headless=True, solve_cloudflare=True) as session:
|
||||
page = session.fetch('https://nopecha.com/demo/cloudflare', google_search=False)
|
||||
data = page.css('#padded_content a')
|
||||
|
||||
# または一回限りのリクエストスタイルを使用、このリクエストのためにブラウザを開き、完了後に閉じる
|
||||
page = StealthyFetcher.fetch('https://nopecha.com/demo/cloudflare')
|
||||
data = page.css('#padded_content a')
|
||||
|
||||
# 完全なブラウザ自動化(完了するまでブラウザを開いたままにする)
|
||||
with DynamicSession(headless=True) as session:
|
||||
page = session.fetch('https://quotes.toscrape.com/', network_idle=True)
|
||||
quotes = page.css('.quote .text::text')
|
||||
|
||||
# または一回限りのリクエストスタイルを使用
|
||||
page = DynamicFetcher.fetch('https://quotes.toscrape.com/', network_idle=True)
|
||||
quotes = page.css('.quote .text::text')
|
||||
```
|
||||
|
||||
### 要素の選択
|
||||
```python
|
||||
# CSSセレクタ
|
||||
page.css('a::text') # テキストを抽出
|
||||
page.css('a::attr(href)') # 属性を抽出
|
||||
page.css('a', recursive=False) # 直接の要素のみ
|
||||
page.css('a', auto_save=True) # 要素の位置を自動保存
|
||||
|
||||
# XPath
|
||||
page.xpath('//a/text()')
|
||||
|
||||
# 柔軟な検索
|
||||
page.find_by_text('Python', first_match=True) # テキストで検索
|
||||
page.find_by_regex(r'\d{4}') # 正規表現パターンで検索
|
||||
page.find('div', {'class': 'container'}) # 属性で検索
|
||||
|
||||
# ナビゲーション
|
||||
element.parent # 親要素を取得
|
||||
element.next_sibling # 次の兄弟を取得
|
||||
element.children # 子要素を取得
|
||||
|
||||
# 類似要素
|
||||
similar = page.get_similar(element) # 類似要素を見つける
|
||||
|
||||
# 適応型スクレイピング
|
||||
saved_elements = page.css('.product', auto_save=True)
|
||||
# 後でウェブサイトが変更されたとき:
|
||||
page.css('.product', adaptive=True) # 保存された位置を使用して要素を見つける
|
||||
```
|
||||
|
||||
### セッションの使用
|
||||
```python
|
||||
from scrapling.fetchers import FetcherSession, AsyncFetcherSession
|
||||
|
||||
# 同期セッション
|
||||
with FetcherSession() as session:
|
||||
# Cookieは自動的に維持されます
|
||||
page1 = session.get('https://quotes.toscrape.com/login')
|
||||
page2 = session.post('https://quotes.toscrape.com/login', data={'username': 'admin', 'password': 'admin'})
|
||||
|
||||
# 必要に応じてブラウザのフィンガープリントを切り替え
|
||||
page2 = session.get('https://quotes.toscrape.com/', impersonate='firefox135')
|
||||
|
||||
# 非同期セッションの使用
|
||||
async with AsyncStealthySession(max_pages=2) as session:
|
||||
tasks = []
|
||||
urls = ['https://example.com/page1', 'https://example.com/page2']
|
||||
|
||||
for url in urls:
|
||||
task = session.fetch(url)
|
||||
tasks.append(task)
|
||||
|
||||
print(session.get_pool_stats()) # オプション - ブラウザタブプールのステータス(ビジー/フリー/エラー)
|
||||
results = await asyncio.gather(*tasks)
|
||||
print(session.get_pool_stats())
|
||||
```
|
||||
|
||||
## CLIとインタラクティブシェル
|
||||
|
||||
Scrapling v0.3には強力なコマンドラインインターフェースが含まれています:
|
||||
|
||||
[](https://asciinema.org/a/736339)
|
||||
|
||||
```bash
|
||||
# インタラクティブウェブスクレイピングシェルを起動
|
||||
scrapling shell
|
||||
|
||||
# プログラミングせずに直接ページをファイルに抽出(デフォルトで`body`タグ内のコンテンツを抽出)
|
||||
# 出力ファイルが`.txt`で終わる場合、ターゲットのテキストコンテンツが抽出されます。
|
||||
# `.md`で終わる場合、HTMLコンテンツのMarkdown表現になり、`.html`は直接HTMLコンテンツになります。
|
||||
scrapling extract get 'https://example.com' content.md
|
||||
scrapling extract get 'https://example.com' content.txt --css-selector '#fromSkipToProducts' --impersonate 'chrome' # CSSセレクタ'#fromSkipToProducts'に一致するすべての要素
|
||||
scrapling extract fetch 'https://example.com' content.md --css-selector '#fromSkipToProducts' --no-headless
|
||||
scrapling extract stealthy-fetch 'https://nopecha.com/demo/cloudflare' captchas.html --css-selector '#padded_content a' --solve-cloudflare
|
||||
```
|
||||
|
||||
> [!NOTE]
|
||||
> MCPサーバーやインタラクティブウェブスクレイピングシェルなど、他にも多くの追加機能がありますが、このページは簡潔に保ちたいと思います。完全なドキュメントは[こちら](https://scrapling.readthedocs.io/en/latest/)をご覧ください
|
||||
|
||||
## パフォーマンスベンチマーク
|
||||
|
||||
Scraplingは強力であるだけでなく、驚くほど高速で、バージョン0.3以降のアップデートはすべての操作で優れたパフォーマンス向上を実現しています。
|
||||
|
||||
### テキスト抽出速度テスト(5000個のネストされた要素)
|
||||
|
||||
| # | ライブラリ | 時間(ms) | vs Scrapling |
|
||||
|---|:-------------------:|:--------:|:------------:|
|
||||
| 1 | Scrapling | 1.92 | 1.0x |
|
||||
| 2 | Parsel/Scrapy | 1.99 | 1.036x |
|
||||
| 3 | Raw Lxml | 2.33 | 1.214x |
|
||||
| 4 | PyQuery | 20.61 | ~11x |
|
||||
| 5 | Selectolax | 80.65 | ~42x |
|
||||
| 6 | BS4 with Lxml | 1283.21 | ~698x |
|
||||
| 7 | MechanicalSoup | 1304.57 | ~679x |
|
||||
| 8 | BS4 with html5lib | 3331.96 | ~1735x |
|
||||
|
||||
### 要素類似性とテキスト検索のパフォーマンス
|
||||
|
||||
Scraplingの適応型要素検索機能は代替手段を大幅に上回ります:
|
||||
|
||||
| ライブラリ | 時間(ms) | vs Scrapling |
|
||||
|-------------|:--------:|:------------:|
|
||||
| Scrapling | 1.87 | 1.0x |
|
||||
| AutoScraper | 10.24 | 5.476x |
|
||||
|
||||
|
||||
> すべてのベンチマークは100回以上の実行の平均を表します。方法論については[benchmarks.py](https://github.com/D4Vinci/Scrapling/blob/main/benchmarks.py)を参照してください。
|
||||
|
||||
## インストール
|
||||
|
||||
ScraplingにはPython 3.10以上が必要です:
|
||||
|
||||
```bash
|
||||
pip install scrapling
|
||||
```
|
||||
|
||||
v0.3.2以降、このインストールにはパーサーエンジンとその依存関係のみが含まれており、フェッチャーやコマンドライン依存関係は含まれていません。
|
||||
|
||||
### オプションの依存関係
|
||||
|
||||
1. 以下の追加機能、フェッチャー、またはそれらのクラスのいずれかを使用する場合は、フェッチャーの依存関係をインストールしてから、次のコマンドでブラウザの依存関係をインストールする必要があります
|
||||
```bash
|
||||
pip install "scrapling[fetchers]"
|
||||
|
||||
scrapling install
|
||||
```
|
||||
|
||||
これにより、すべてのブラウザとそのシステム依存関係およびフィンガープリント操作依存関係がダウンロードされます。
|
||||
|
||||
2. 追加機能:
|
||||
- MCPサーバー機能をインストール:
|
||||
```bash
|
||||
pip install "scrapling[ai]"
|
||||
```
|
||||
- シェル機能(ウェブスクレイピングシェルと`extract`コマンド)をインストール:
|
||||
```bash
|
||||
pip install "scrapling[shell]"
|
||||
```
|
||||
- すべてをインストール:
|
||||
```bash
|
||||
pip install "scrapling[all]"
|
||||
```
|
||||
これらの追加機能のいずれかの後(まだインストールしていない場合)、`scrapling install`でブラウザの依存関係をインストールする必要があることを忘れないでください
|
||||
|
||||
### Docker
|
||||
DockerHubから次のコマンドですべての追加機能とブラウザを含むDockerイメージをインストールすることもできます:
|
||||
```bash
|
||||
docker pull pyd4vinci/scrapling
|
||||
```
|
||||
またはGitHubレジストリからダウンロード:
|
||||
```bash
|
||||
docker pull ghcr.io/d4vinci/scrapling:latest
|
||||
```
|
||||
このイメージは、リポジトリのメインブランチでGitHub actionsを通じて自動的にビルドおよびプッシュされます。
|
||||
|
||||
## 貢献
|
||||
|
||||
貢献を歓迎します!始める前に[貢献ガイドライン](https://github.com/D4Vinci/Scrapling/blob/main/CONTRIBUTING.md)をお読みください。
|
||||
|
||||
## 免責事項
|
||||
|
||||
> [!CAUTION]
|
||||
> このライブラリは教育および研究目的のみで提供されています。このライブラリを使用することにより、地域および国際的なデータスクレイピングおよびプライバシー法に準拠することに同意したものとみなされます。著者および貢献者は、このソフトウェアの誤用について責任を負いません。常にウェブサイトの利用規約とrobots.txtファイルを尊重してください。
|
||||
|
||||
## ライセンス
|
||||
|
||||
この作品はBSD-3-Clauseライセンスの下でライセンスされています。
|
||||
|
||||
## 謝辞
|
||||
|
||||
このプロジェクトには次から適応されたコードが含まれています:
|
||||
- Parsel(BSDライセンス)— [translator](https://github.com/D4Vinci/Scrapling/blob/main/scrapling/core/translator.py)サブモジュールに使用
|
||||
|
||||
## 感謝と参考文献
|
||||
|
||||
- [Daijro](https://github.com/daijro)の[BrowserForge](https://github.com/daijro/browserforge)と[Camoufox](https://github.com/daijro/camoufox)における素晴らしい仕事
|
||||
- [Vinyzu](https://github.com/Vinyzu)の[Botright](https://github.com/Vinyzu/Botright)と[PatchRight](https://github.com/Kaliiiiiiiiii-Vinyzu/patchright)における素晴らしい仕事
|
||||
- ブラウザ検出回避技術を提供する[brotector](https://github.com/kaliiiiiiiiii/brotector)
|
||||
- フィンガープリント研究を提供する[fakebrowser](https://github.com/kkoooqq/fakebrowser)と[BotBrowser](https://github.com/botswin/BotBrowser)
|
||||
|
||||
---
|
||||
<div align="center"><small>Karim Shoairによって❤️でデザインおよび作成されました。</small></div><br>
|
||||
@@ -0,0 +1,332 @@
|
||||
<p align=center>
|
||||
<br>
|
||||
<a href="https://scrapling.readthedocs.io/en/latest/" target="_blank"><img src="https://raw.githubusercontent.com/D4Vinci/Scrapling/main/images/poster.png" style="width: 50%; height: 100%;" alt="main poster"/></a>
|
||||
<br>
|
||||
<i><code>Простой, легкий веб-скрапинг, каким он и должен быть!</code></i>
|
||||
</p>
|
||||
<p align="center">
|
||||
<a href="https://github.com/D4Vinci/Scrapling/actions/workflows/tests.yml" alt="Tests">
|
||||
<img alt="Tests" src="https://github.com/D4Vinci/Scrapling/actions/workflows/tests.yml/badge.svg"></a>
|
||||
<a href="https://badge.fury.io/py/Scrapling" alt="PyPI version">
|
||||
<img alt="PyPI version" src="https://badge.fury.io/py/Scrapling.svg"></a>
|
||||
<a href="https://pepy.tech/project/scrapling" alt="PyPI Downloads">
|
||||
<img alt="PyPI Downloads" src="https://static.pepy.tech/personalized-badge/scrapling?period=total&units=INTERNATIONAL_SYSTEM&left_color=GREY&right_color=GREEN&left_text=Downloads"></a>
|
||||
<br/>
|
||||
<a href="https://discord.gg/EMgGbDceNQ" alt="Discord" target="_blank">
|
||||
<img alt="Discord" src="https://img.shields.io/discord/1360786381042880532?style=social&logo=discord&link=https%3A%2F%2Fdiscord.gg%2FEMgGbDceNQ">
|
||||
</a>
|
||||
<a href="https://x.com/Scrapling_dev" alt="X (formerly Twitter)">
|
||||
<img alt="X (formerly Twitter) Follow" src="https://img.shields.io/twitter/follow/Scrapling_dev?style=social&logo=x&link=https%3A%2F%2Fx.com%2FScrapling_dev">
|
||||
</a>
|
||||
<br/>
|
||||
<a href="https://pypi.org/project/scrapling/" alt="Supported Python versions">
|
||||
<img alt="Supported Python versions" src="https://img.shields.io/pypi/pyversions/scrapling.svg"></a>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<a href="https://scrapling.readthedocs.io/en/latest/parsing/selection/">
|
||||
Методы выбора
|
||||
</a>
|
||||
·
|
||||
<a href="https://scrapling.readthedocs.io/en/latest/fetching/choosing/">
|
||||
Выбор фетчера
|
||||
</a>
|
||||
·
|
||||
<a href="https://scrapling.readthedocs.io/en/latest/cli/overview/">
|
||||
CLI
|
||||
</a>
|
||||
·
|
||||
<a href="https://scrapling.readthedocs.io/en/latest/ai/mcp-server/">
|
||||
Режим MCP
|
||||
</a>
|
||||
·
|
||||
<a href="https://scrapling.readthedocs.io/en/latest/tutorials/migrating_from_beautifulsoup/">
|
||||
Миграция с Beautifulsoup
|
||||
</a>
|
||||
</p>
|
||||
|
||||
**Прекратите бороться с анти-ботовыми системами. Прекратите переписывать селекторы после каждого обновления сайта.**
|
||||
|
||||
Scrapling - это не просто очередная библиотека для веб-скрапинга. Это первая **адаптивная** библиотека для скрапинга, которая учится на изменениях сайтов и развивается вместе с ними. В то время как другие библиотеки ломаются, когда сайты обновляют свою структуру, Scrapling автоматически перемещает ваши элементы и поддерживает работу ваших скраперов.
|
||||
|
||||
Созданный для современного веба, Scrapling имеет **собственный быстрый движок парсинга** и фетчеры для решения всех задач веб-скрапинга, с которыми вы сталкиваетесь или столкнетесь. Созданный веб-скраперами для веб-скраперов и обычных пользователей, здесь есть что-то для каждого.
|
||||
|
||||
```python
|
||||
>> from scrapling.fetchers import Fetcher, AsyncFetcher, StealthyFetcher, DynamicFetcher
|
||||
>> StealthyFetcher.adaptive = True
|
||||
# Получайте исходный код сайтов незаметно!
|
||||
>> page = StealthyFetcher.fetch('https://example.com', headless=True, network_idle=True)
|
||||
>> print(page.status)
|
||||
200
|
||||
>> products = page.css('.product', auto_save=True) # Скрапьте данные, которые переживут изменения дизайна сайта!
|
||||
>> # Позже, если структура сайта изменится, передайте `adaptive=True`
|
||||
>> products = page.css('.product', adaptive=True) # и Scrapling все равно их найдет!
|
||||
```
|
||||
|
||||
# Спонсоры
|
||||
|
||||
<!-- sponsors -->
|
||||
|
||||
<a href="https://www.scrapeless.com/en?utm_source=official&utm_term=scrapling" target="_blank" title="Effortless Web Scraping Toolkit for Business and Developers"><img src="https://raw.githubusercontent.com/D4Vinci/Scrapling/main/images/scrapeless.jpg"></a>
|
||||
<a href="https://evomi.com?utm_source=github&utm_medium=banner&utm_campaign=d4vinci-scrapling" target="_blank" title="Evomi is your Swiss Quality Proxy Provider, starting at $0.49/GB"><img src="https://raw.githubusercontent.com/D4Vinci/Scrapling/main/images/evomi.png"></a>
|
||||
<a href="https://visit.decodo.com/Dy6W0b" target="_blank" title="Try the Most Efficient Residential Proxies for Free"><img src="https://raw.githubusercontent.com/D4Vinci/Scrapling/main/images/decodo.png"></a>
|
||||
<a href="https://petrosky.io/d4vinci" target="_blank" title="PetroSky delivers cutting-edge VPS hosting."><img src="https://raw.githubusercontent.com/D4Vinci/Scrapling/main/images/petrosky.png"></a>
|
||||
<a href="https://app.cyberyozh.com/?utm_source=github&utm_medium=scrapling" target="_blank" title="We have gathered the best solutions for multi‑accounting and automation in one place."><img src="https://raw.githubusercontent.com/D4Vinci/Scrapling/main/images/cyberyozh.png"></a>
|
||||
<a href="https://www.swiftproxy.net/" target="_blank" title="Unlock Reliable Proxy Services with Swiftproxy!"><img src="https://raw.githubusercontent.com/D4Vinci/Scrapling/main/images/swiftproxy.png"></a>
|
||||
<a href="https://www.rapidproxy.io/?ref=d4v" target="_blank" title="Affordable Access to the Proxy World – bypass CAPTCHAs blocks, and avoid additional costs."><img src="https://raw.githubusercontent.com/D4Vinci/Scrapling/main/images/rapidproxy.jpg"></a>
|
||||
<a href="https://serpapi.com/?utm_source=scrapling" target="_blank" title="Scrape Google and other search engines with SerpApi"><img src="https://raw.githubusercontent.com/D4Vinci/Scrapling/main/images/SerpApi.png"></a>
|
||||
|
||||
<!-- /sponsors -->
|
||||
|
||||
<i><sub>Хотите показать здесь свою рекламу? Нажмите [здесь](https://github.com/sponsors/D4Vinci) и выберите подходящий вам уровень!</sub></i>
|
||||
|
||||
---
|
||||
|
||||
## Ключевые особенности
|
||||
|
||||
### Продвинутая загрузка сайтов с поддержкой сессий
|
||||
- **HTTP-запросы**: Быстрые и скрытные HTTP-запросы с классом `Fetcher`. Может имитировать TLS-отпечаток браузера, заголовки и использовать HTTP3.
|
||||
- **Динамическая загрузка**: Загрузка динамических сайтов с полной автоматизацией браузера через класс `DynamicFetcher`, поддерживающий Chromium от Playwright, настоящий Chrome и пользовательский режим скрытности.
|
||||
- **Обход анти-ботов**: Расширенные возможности скрытности с `StealthyFetcher`, использующим модифицированную версию Firefox и подмену отпечатков. Может легко обойти все типы Turnstile и Interstitial от Cloudflare с помощью автоматизации.
|
||||
- **Управление сессиями**: Поддержка постоянных сессий с классами `FetcherSession`, `StealthySession` и `DynamicSession` для управления cookie и состоянием между запросами.
|
||||
- **Поддержка асинхронности**: Полная асинхронная поддержка во всех фетчерах и выделенных асинхронных классах сессий.
|
||||
|
||||
### Адаптивный скрапинг и интеграция с ИИ
|
||||
- 🔄 **Умное отслеживание элементов**: Перемещайте элементы после изменений сайта с помощью интеллектуальных алгоритмов подобия.
|
||||
- 🎯 **Умный гибкий выбор**: CSS-селекторы, XPath-селекторы, поиск на основе фильтров, текстовый поиск, поиск по регулярным выражениям и многое другое.
|
||||
- 🔍 **Поиск похожих элементов**: Автоматически находите элементы, похожие на найденные элементы.
|
||||
- 🤖 **MCP-сервер для использования с ИИ**: Встроенный MCP-сервер для веб-скрапинга с помощью ИИ и извлечения данных. MCP-сервер обладает пользовательскими, мощными возможностями, которые используют Scrapling для извлечения целевого контента перед передачей его ИИ (Claude/Cursor/и т.д.), тем самым ускоряя операции и снижая затраты за счет минимизации использования токенов. ([демо-видео](https://www.youtube.com/watch?v=qyFk3ZNwOxE))
|
||||
|
||||
### Высокопроизводительная и проверенная в боях архитектура
|
||||
- 🚀 **Молниеносно быстро**: Оптимизированная производительность превосходит большинство библиотек скрапинга Python.
|
||||
- 🔋 **Эффективное использование памяти**: Оптимизированные структуры данных и ленивая загрузка для минимального потребления памяти.
|
||||
- ⚡ **Быстрая сериализация JSON**: В 10 раз быстрее, чем стандартная библиотека.
|
||||
- 🏗️ **Проверено в боях**: Scrapling имеет не только 92% покрытия тестами и полное покрытие type hints, но и ежедневно использовался сотнями веб-скраперов в течение последнего года.
|
||||
|
||||
### Удобный для разработчиков/веб-скраперов опыт
|
||||
- 🎯 **Интерактивная оболочка веб-скрапинга**: Опциональная встроенная оболочка IPython с интеграцией Scrapling, ярлыками и новыми инструментами для ускорения разработки скриптов веб-скрапинга, такими как преобразование curl-запросов в Scrapling-запросы и просмотр результатов запросов в вашем браузере.
|
||||
- 🚀 **Используйте прямо из терминала**: При желании вы можете использовать Scrapling для скрапинга URL без написания ни одной строки кода!
|
||||
- 🛠️ **Богатый API навигации**: Расширенный обход DOM с методами навигации по родителям, братьям и детям.
|
||||
- 🧬 **Улучшенная обработка текста**: Встроенные регулярные выражения, методы очистки и оптимизированные операции со строками.
|
||||
- 📝 **Автоматическая генерация селекторов**: Генерация надежных CSS/XPath селекторов для любого элемента.
|
||||
- 🔌 **Знакомый API**: Похож на Scrapy/BeautifulSoup с теми же псевдоэлементами, используемыми в Scrapy/Parsel.
|
||||
- 📘 **Полное покрытие типами**: Полные подсказки типов для отличной поддержки IDE и автодополнения кода.
|
||||
- 🔋 **Готовый Docker-образ**: С каждым релизом автоматически создается и отправляется Docker-образ, содержащий все браузеры.
|
||||
|
||||
## Начало работы
|
||||
|
||||
### Базовое использование
|
||||
```python
|
||||
from scrapling.fetchers import Fetcher, StealthyFetcher, DynamicFetcher
|
||||
from scrapling.fetchers import FetcherSession, StealthySession, DynamicSession
|
||||
|
||||
# HTTP-запросы с поддержкой сессий
|
||||
with FetcherSession(impersonate='chrome') as session: # Используйте последнюю версию TLS-отпечатка Chrome
|
||||
page = session.get('https://quotes.toscrape.com/', stealthy_headers=True)
|
||||
quotes = page.css('.quote .text::text')
|
||||
|
||||
# Или используйте одноразовые запросы
|
||||
page = Fetcher.get('https://quotes.toscrape.com/')
|
||||
quotes = page.css('.quote .text::text')
|
||||
|
||||
# Расширенный режим скрытности (Держите браузер открытым до завершения)
|
||||
with StealthySession(headless=True, solve_cloudflare=True) as session:
|
||||
page = session.fetch('https://nopecha.com/demo/cloudflare', google_search=False)
|
||||
data = page.css('#padded_content a')
|
||||
|
||||
# Или используйте стиль одноразового запроса, открывает браузер для этого запроса, затем закрывает его после завершения
|
||||
page = StealthyFetcher.fetch('https://nopecha.com/demo/cloudflare')
|
||||
data = page.css('#padded_content a')
|
||||
|
||||
# Полная автоматизация браузера (Держите браузер открытым до завершения)
|
||||
with DynamicSession(headless=True) as session:
|
||||
page = session.fetch('https://quotes.toscrape.com/', network_idle=True)
|
||||
quotes = page.css('.quote .text::text')
|
||||
|
||||
# Или используйте стиль одноразового запроса
|
||||
page = DynamicFetcher.fetch('https://quotes.toscrape.com/', network_idle=True)
|
||||
quotes = page.css('.quote .text::text')
|
||||
```
|
||||
|
||||
### Выбор элементов
|
||||
```python
|
||||
# CSS-селекторы
|
||||
page.css('a::text') # Извлечь текст
|
||||
page.css('a::attr(href)') # Извлечь атрибуты
|
||||
page.css('a', recursive=False) # Только прямые элементы
|
||||
page.css('a', auto_save=True) # Автоматически сохранять позиции элементов
|
||||
|
||||
# XPath
|
||||
page.xpath('//a/text()')
|
||||
|
||||
# Гибкий поиск
|
||||
page.find_by_text('Python', first_match=True) # Найти по тексту
|
||||
page.find_by_regex(r'\d{4}') # Найти по паттерну regex
|
||||
page.find('div', {'class': 'container'}) # Найти по атрибутам
|
||||
|
||||
# Навигация
|
||||
element.parent # Получить родительский элемент
|
||||
element.next_sibling # Получить следующего брата
|
||||
element.children # Получить дочерние элементы
|
||||
|
||||
# Похожие элементы
|
||||
similar = page.get_similar(element) # Найти похожие элементы
|
||||
|
||||
# Адаптивный скрапинг
|
||||
saved_elements = page.css('.product', auto_save=True)
|
||||
# Позже, когда сайт изменится:
|
||||
page.css('.product', adaptive=True) # Найти элементы используя сохраненные позиции
|
||||
```
|
||||
|
||||
### Использование сессий
|
||||
```python
|
||||
from scrapling.fetchers import FetcherSession, AsyncFetcherSession
|
||||
|
||||
# Синхронная сессия
|
||||
with FetcherSession() as session:
|
||||
# Cookie автоматически сохраняются
|
||||
page1 = session.get('https://quotes.toscrape.com/login')
|
||||
page2 = session.post('https://quotes.toscrape.com/login', data={'username': 'admin', 'password': 'admin'})
|
||||
|
||||
# При необходимости переключите отпечаток браузера
|
||||
page2 = session.get('https://quotes.toscrape.com/', impersonate='firefox135')
|
||||
|
||||
# Использование асинхронной сессии
|
||||
async with AsyncStealthySession(max_pages=2) as session:
|
||||
tasks = []
|
||||
urls = ['https://example.com/page1', 'https://example.com/page2']
|
||||
|
||||
for url in urls:
|
||||
task = session.fetch(url)
|
||||
tasks.append(task)
|
||||
|
||||
print(session.get_pool_stats()) # Опционально - Статус пула вкладок браузера (занят/свободен/ошибка)
|
||||
results = await asyncio.gather(*tasks)
|
||||
print(session.get_pool_stats())
|
||||
```
|
||||
|
||||
## CLI и интерактивная оболочка
|
||||
|
||||
Scrapling v0.3 включает мощный интерфейс командной строки:
|
||||
|
||||
[](https://asciinema.org/a/736339)
|
||||
|
||||
```bash
|
||||
# Запустить интерактивную оболочку веб-скрапинга
|
||||
scrapling shell
|
||||
|
||||
# Извлечь страницы в файл напрямую без программирования (Извлекает содержимое внутри тега `body` по умолчанию)
|
||||
# Если выходной файл заканчивается на `.txt`, то будет извлечено текстовое содержимое цели.
|
||||
# Если заканчивается на `.md`, это будет markdown-представление HTML-содержимого, а `.html` будет непосредственно HTML-содержимым.
|
||||
scrapling extract get 'https://example.com' content.md
|
||||
scrapling extract get 'https://example.com' content.txt --css-selector '#fromSkipToProducts' --impersonate 'chrome' # Все элементы, соответствующие CSS-селектору '#fromSkipToProducts'
|
||||
scrapling extract fetch 'https://example.com' content.md --css-selector '#fromSkipToProducts' --no-headless
|
||||
scrapling extract stealthy-fetch 'https://nopecha.com/demo/cloudflare' captchas.html --css-selector '#padded_content a' --solve-cloudflare
|
||||
```
|
||||
|
||||
> [!NOTE]
|
||||
> Есть много дополнительных функций, но мы хотим сохранить эту страницу краткой, например, MCP-сервер и интерактивная оболочка веб-скрапинга. Ознакомьтесь с полной документацией [здесь](https://scrapling.readthedocs.io/en/latest/)
|
||||
|
||||
## Тесты производительности
|
||||
|
||||
Scrapling не только мощный - он также невероятно быстрый, и обновления с версии 0.3 обеспечили исключительные улучшения производительности во всех операциях.
|
||||
|
||||
### Тест скорости извлечения текста (5000 вложенных элементов)
|
||||
|
||||
| # | Библиотека | Время (мс) | vs Scrapling |
|
||||
|---|:--------------------:|:----------:|:------------:|
|
||||
| 1 | Scrapling | 1.92 | 1.0x |
|
||||
| 2 | Parsel/Scrapy | 1.99 | 1.036x |
|
||||
| 3 | Raw Lxml | 2.33 | 1.214x |
|
||||
| 4 | PyQuery | 20.61 | ~11x |
|
||||
| 5 | Selectolax | 80.65 | ~42x |
|
||||
| 6 | BS4 с Lxml | 1283.21 | ~698x |
|
||||
| 7 | MechanicalSoup | 1304.57 | ~679x |
|
||||
| 8 | BS4 с html5lib | 3331.96 | ~1735x |
|
||||
|
||||
### Производительность подобия элементов и текстового поиска
|
||||
|
||||
Возможности адаптивного поиска элементов Scrapling значительно превосходят альтернативы:
|
||||
|
||||
| Библиотека | Время (мс) | vs Scrapling |
|
||||
|-------------|:----------:|:------------:|
|
||||
| Scrapling | 1.87 | 1.0x |
|
||||
| AutoScraper | 10.24 | 5.476x |
|
||||
|
||||
|
||||
> Все тесты производительности представляют собой средние значения более 100 запусков. См. [benchmarks.py](https://github.com/D4Vinci/Scrapling/blob/main/benchmarks.py) для методологии.
|
||||
|
||||
## Установка
|
||||
|
||||
Scrapling требует Python 3.10 или выше:
|
||||
|
||||
```bash
|
||||
pip install scrapling
|
||||
```
|
||||
|
||||
Начиная с v0.3.2, эта установка включает только движок парсера и его зависимости, без каких-либо фетчеров или зависимостей командной строки.
|
||||
|
||||
### Опциональные зависимости
|
||||
|
||||
1. Если вы собираетесь использовать какие-либо из дополнительных функций ниже, фетчеры или их классы, то вам нужно установить зависимости фетчеров, а затем установить их зависимости браузера с помощью
|
||||
```bash
|
||||
pip install "scrapling[fetchers]"
|
||||
|
||||
scrapling install
|
||||
```
|
||||
|
||||
Это загрузит все браузеры с их системными зависимостями и зависимостями манипуляции отпечатками.
|
||||
|
||||
2. Дополнительные функции:
|
||||
- Установить функцию MCP-сервера:
|
||||
```bash
|
||||
pip install "scrapling[ai]"
|
||||
```
|
||||
- Установить функции оболочки (оболочка веб-скрапинга и команда `extract`):
|
||||
```bash
|
||||
pip install "scrapling[shell]"
|
||||
```
|
||||
- Установить все:
|
||||
```bash
|
||||
pip install "scrapling[all]"
|
||||
```
|
||||
Помните, что вам нужно установить зависимости браузера с помощью `scrapling install` после любого из этих дополнений (если вы еще этого не сделали)
|
||||
|
||||
### Docker
|
||||
Вы также можете установить Docker-образ со всеми дополнениями и браузерами с помощью следующей команды из DockerHub:
|
||||
```bash
|
||||
docker pull pyd4vinci/scrapling
|
||||
```
|
||||
Или скачайте его из реестра GitHub:
|
||||
```bash
|
||||
docker pull ghcr.io/d4vinci/scrapling:latest
|
||||
```
|
||||
Этот образ автоматически создается и отправляется через GitHub actions в основной ветке репозитория.
|
||||
|
||||
## Вклад
|
||||
|
||||
Мы приветствуем вклад! Пожалуйста, прочитайте наши [руководства по внесению вклада](https://github.com/D4Vinci/Scrapling/blob/main/CONTRIBUTING.md) перед началом работы.
|
||||
|
||||
## Отказ от ответственности
|
||||
|
||||
> [!CAUTION]
|
||||
> Эта библиотека предоставляется только в образовательных и исследовательских целях. Используя эту библиотеку, вы соглашаетесь соблюдать местные и международные законы о скрапинге данных и конфиденциальности. Авторы и участники не несут ответственности за любое неправомерное использование этого программного обеспечения. Всегда уважайте условия обслуживания веб-сайтов и файлы robots.txt.
|
||||
|
||||
## Лицензия
|
||||
|
||||
Эта работа лицензирована по лицензии BSD-3-Clause.
|
||||
|
||||
## Благодарности
|
||||
|
||||
Этот проект включает код, адаптированный из:
|
||||
- Parsel (лицензия BSD) — Используется для подмодуля [translator](https://github.com/D4Vinci/Scrapling/blob/main/scrapling/core/translator.py)
|
||||
|
||||
## Благодарности и ссылки
|
||||
|
||||
- Блестящая работа [Daijro](https://github.com/daijro) над [BrowserForge](https://github.com/daijro/browserforge) и [Camoufox](https://github.com/daijro/camoufox)
|
||||
- Блестящая работа [Vinyzu](https://github.com/Vinyzu) над [Botright](https://github.com/Vinyzu/Botright) и [PatchRight](https://github.com/Kaliiiiiiiiii-Vinyzu/patchright)
|
||||
- [brotector](https://github.com/kaliiiiiiiiii/brotector) за техники обхода обнаружения браузера
|
||||
- [fakebrowser](https://github.com/kkoooqq/fakebrowser) и [BotBrowser](https://github.com/botswin/BotBrowser) за исследование отпечатков
|
||||
|
||||
---
|
||||
<div align="center"><small>Разработано и создано с ❤️ Карим Шоаир.</small></div><br>
|
||||
+1
-1
@@ -7,7 +7,7 @@ name = "scrapling"
|
||||
# Static version instead of a dynamic version so we can get better layer caching while building docker, check the docker file to understand
|
||||
version = "0.3.9"
|
||||
description = "Scrapling is an undetectable, powerful, flexible, high-performance Python library that makes Web Scraping easy and effortless as it should be!"
|
||||
readme = {file = "README.md", content-type = "text/markdown"}
|
||||
readme = {file = "docs/README.md", content-type = "text/markdown"}
|
||||
license = {file = "LICENSE"}
|
||||
authors = [
|
||||
{name = "Karim Shoair", email = "karim.shoair@pm.me"}
|
||||
|
||||
Reference in New Issue
Block a user