scrapingrabbit 0.1.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- scrapingrabbit-0.1.0/.github/workflows/publish.yml +45 -0
- scrapingrabbit-0.1.0/.gitignore +6 -0
- scrapingrabbit-0.1.0/LICENSE +21 -0
- scrapingrabbit-0.1.0/PKG-INFO +83 -0
- scrapingrabbit-0.1.0/README.md +65 -0
- scrapingrabbit-0.1.0/pyproject.toml +27 -0
- scrapingrabbit-0.1.0/scrapingrabbit/__init__.py +5 -0
- scrapingrabbit-0.1.0/scrapingrabbit/_methods.py +258 -0
- scrapingrabbit-0.1.0/scrapingrabbit/client.py +127 -0
- scrapingrabbit-0.1.0/scrapingrabbit/py.typed +0 -0
- scrapingrabbit-0.1.0/scripts/generate.py +67 -0
- scrapingrabbit-0.1.0/tests/test_client.py +114 -0
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
name: Publish to PyPI
|
|
2
|
+
|
|
3
|
+
# Push a version tag (for example v0.1.0 after bumping `version` in pyproject.toml) and this publishes that commit.
|
|
4
|
+
# No PyPI token is stored: PyPI trusts this workflow through "trusted publishing" (OIDC), set once on pypi.org
|
|
5
|
+
# (repo pushkarsingh32/scrapingrabbit-python, workflow publish.yml, environment pypi).
|
|
6
|
+
on:
|
|
7
|
+
push:
|
|
8
|
+
tags: ["v*"]
|
|
9
|
+
|
|
10
|
+
permissions:
|
|
11
|
+
contents: read
|
|
12
|
+
|
|
13
|
+
jobs:
|
|
14
|
+
build:
|
|
15
|
+
runs-on: ubuntu-latest
|
|
16
|
+
steps:
|
|
17
|
+
- uses: actions/checkout@v4
|
|
18
|
+
- uses: actions/setup-python@v5
|
|
19
|
+
with:
|
|
20
|
+
python-version: "3.12"
|
|
21
|
+
- name: Tag must match pyproject.toml
|
|
22
|
+
run: |
|
|
23
|
+
PKG="v$(python -c "import tomllib;print(tomllib.load(open('pyproject.toml','rb'))['project']['version'])")"
|
|
24
|
+
if [ "$GITHUB_REF_NAME" != "$PKG" ]; then echo "Tag $GITHUB_REF_NAME does not match pyproject.toml $PKG"; exit 1; fi
|
|
25
|
+
- run: python -m pip install build twine .
|
|
26
|
+
- run: python -m unittest discover -s tests
|
|
27
|
+
- run: python -m build
|
|
28
|
+
- run: python -m twine check --strict dist/*
|
|
29
|
+
- uses: actions/upload-artifact@v4
|
|
30
|
+
with:
|
|
31
|
+
name: dist
|
|
32
|
+
path: dist/
|
|
33
|
+
|
|
34
|
+
publish:
|
|
35
|
+
needs: build
|
|
36
|
+
runs-on: ubuntu-latest
|
|
37
|
+
environment: pypi
|
|
38
|
+
permissions:
|
|
39
|
+
id-token: write
|
|
40
|
+
steps:
|
|
41
|
+
- uses: actions/download-artifact@v4
|
|
42
|
+
with:
|
|
43
|
+
name: dist
|
|
44
|
+
path: dist/
|
|
45
|
+
- uses: pypa/gh-action-pypi-publish@release/v1
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 ScrapingRabbit
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: scrapingrabbit
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Python client for the ScrapingRabbit web data API: YouTube transcripts and comments, TikTok, Instagram, X, Amazon, Google and SEO data.
|
|
5
|
+
Project-URL: Homepage, https://scrapingrabbit.com
|
|
6
|
+
Project-URL: Documentation, https://scrapingrabbit.com/docs
|
|
7
|
+
Project-URL: Repository, https://github.com/pushkarsingh32/scrapingrabbit-python
|
|
8
|
+
Project-URL: Issues, https://github.com/pushkarsingh32/scrapingrabbit-python/issues
|
|
9
|
+
License-Expression: MIT
|
|
10
|
+
License-File: LICENSE
|
|
11
|
+
Keywords: api,instagram,scraping,seo,tiktok,web-data,youtube-transcript
|
|
12
|
+
Classifier: Operating System :: OS Independent
|
|
13
|
+
Classifier: Programming Language :: Python :: 3
|
|
14
|
+
Classifier: Typing :: Typed
|
|
15
|
+
Requires-Python: >=3.9
|
|
16
|
+
Requires-Dist: httpx>=0.24
|
|
17
|
+
Description-Content-Type: text/markdown
|
|
18
|
+
|
|
19
|
+
# scrapingrabbit
|
|
20
|
+
|
|
21
|
+
Python client for the [ScrapingRabbit](https://scrapingrabbit.com) web data API: YouTube transcripts and comments, TikTok, Instagram, X, Amazon, Google and SEO data as JSON.
|
|
22
|
+
|
|
23
|
+
- One method per API endpoint (31), generated from the API's [OpenAPI file](https://scrapingrabbit.com/openapi.json).
|
|
24
|
+
- Sync and async clients. Rate limits (`429`) and server errors are retried; refusals are not.
|
|
25
|
+
- You pay credits only when a call returns data. Failed calls are free, so retrying is safe.
|
|
26
|
+
- New accounts get 100 free credits and a first key, no card needed: [scrapingrabbit.com/login](https://scrapingrabbit.com/login).
|
|
27
|
+
|
|
28
|
+
## Install
|
|
29
|
+
|
|
30
|
+
The package is not on PyPI yet, so install it straight from GitHub:
|
|
31
|
+
|
|
32
|
+
```bash
|
|
33
|
+
pip install "git+https://github.com/pushkarsingh32/scrapingrabbit-python.git"
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
## Use
|
|
37
|
+
|
|
38
|
+
```python
|
|
39
|
+
from scrapingrabbit import ScrapingRabbit, ScrapingRabbitError
|
|
40
|
+
|
|
41
|
+
client = ScrapingRabbit() # reads SCRAPINGRABBIT_API_KEY, or pass api_key="sr_live_..."
|
|
42
|
+
|
|
43
|
+
try:
|
|
44
|
+
transcript = client.youtube_transcript(url="https://www.youtube.com/watch?v=dQw4w9WgXcQ")
|
|
45
|
+
print(transcript["language"], len(transcript["transcript"]), "lines")
|
|
46
|
+
except ScrapingRabbitError as error:
|
|
47
|
+
print(error.code, error.message) # for example UPSTREAM_NOT_FOUND when a video has no captions
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
Async:
|
|
51
|
+
|
|
52
|
+
```python
|
|
53
|
+
import asyncio
|
|
54
|
+
from scrapingrabbit import AsyncScrapingRabbit
|
|
55
|
+
|
|
56
|
+
async def main():
|
|
57
|
+
async with AsyncScrapingRabbit() as client:
|
|
58
|
+
print(await client.tiktok_username_checker(username="example"))
|
|
59
|
+
|
|
60
|
+
asyncio.run(main())
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
Comments come one page at a time. Pass the token from the previous answer to get the next page:
|
|
64
|
+
|
|
65
|
+
```python
|
|
66
|
+
page = client.youtube_comment_extractor(url=video_url)
|
|
67
|
+
more = client.youtube_comment_extractor(url=video_url, next_page_token=page["pagination"]["next_page_token"])
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
## Errors
|
|
71
|
+
|
|
72
|
+
`ScrapingRabbitError` has `.code` (for example `RATE_LIMITED`, `PAYMENT_REQUIRED`, `INVALID_PARAMETERS`), `.message`, `.status` and `.retry_after`. The full list is in the [docs](https://scrapingrabbit.com/docs).
|
|
73
|
+
|
|
74
|
+
## Develop
|
|
75
|
+
|
|
76
|
+
```bash
|
|
77
|
+
python scripts/generate.py # refresh scrapingrabbit/_methods.py from the live OpenAPI file
|
|
78
|
+
python -m unittest discover -s tests # runs the client against a fake API
|
|
79
|
+
```
|
|
80
|
+
|
|
81
|
+
## License
|
|
82
|
+
|
|
83
|
+
MIT
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
# scrapingrabbit
|
|
2
|
+
|
|
3
|
+
Python client for the [ScrapingRabbit](https://scrapingrabbit.com) web data API: YouTube transcripts and comments, TikTok, Instagram, X, Amazon, Google and SEO data as JSON.
|
|
4
|
+
|
|
5
|
+
- One method per API endpoint (31), generated from the API's [OpenAPI file](https://scrapingrabbit.com/openapi.json).
|
|
6
|
+
- Sync and async clients. Rate limits (`429`) and server errors are retried; refusals are not.
|
|
7
|
+
- You pay credits only when a call returns data. Failed calls are free, so retrying is safe.
|
|
8
|
+
- New accounts get 100 free credits and a first key, no card needed: [scrapingrabbit.com/login](https://scrapingrabbit.com/login).
|
|
9
|
+
|
|
10
|
+
## Install
|
|
11
|
+
|
|
12
|
+
The package is not on PyPI yet, so install it straight from GitHub:
|
|
13
|
+
|
|
14
|
+
```bash
|
|
15
|
+
pip install "git+https://github.com/pushkarsingh32/scrapingrabbit-python.git"
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
## Use
|
|
19
|
+
|
|
20
|
+
```python
|
|
21
|
+
from scrapingrabbit import ScrapingRabbit, ScrapingRabbitError
|
|
22
|
+
|
|
23
|
+
client = ScrapingRabbit() # reads SCRAPINGRABBIT_API_KEY, or pass api_key="sr_live_..."
|
|
24
|
+
|
|
25
|
+
try:
|
|
26
|
+
transcript = client.youtube_transcript(url="https://www.youtube.com/watch?v=dQw4w9WgXcQ")
|
|
27
|
+
print(transcript["language"], len(transcript["transcript"]), "lines")
|
|
28
|
+
except ScrapingRabbitError as error:
|
|
29
|
+
print(error.code, error.message) # for example UPSTREAM_NOT_FOUND when a video has no captions
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
Async:
|
|
33
|
+
|
|
34
|
+
```python
|
|
35
|
+
import asyncio
|
|
36
|
+
from scrapingrabbit import AsyncScrapingRabbit
|
|
37
|
+
|
|
38
|
+
async def main():
|
|
39
|
+
async with AsyncScrapingRabbit() as client:
|
|
40
|
+
print(await client.tiktok_username_checker(username="example"))
|
|
41
|
+
|
|
42
|
+
asyncio.run(main())
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
Comments come one page at a time. Pass the token from the previous answer to get the next page:
|
|
46
|
+
|
|
47
|
+
```python
|
|
48
|
+
page = client.youtube_comment_extractor(url=video_url)
|
|
49
|
+
more = client.youtube_comment_extractor(url=video_url, next_page_token=page["pagination"]["next_page_token"])
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
## Errors
|
|
53
|
+
|
|
54
|
+
`ScrapingRabbitError` has `.code` (for example `RATE_LIMITED`, `PAYMENT_REQUIRED`, `INVALID_PARAMETERS`), `.message`, `.status` and `.retry_after`. The full list is in the [docs](https://scrapingrabbit.com/docs).
|
|
55
|
+
|
|
56
|
+
## Develop
|
|
57
|
+
|
|
58
|
+
```bash
|
|
59
|
+
python scripts/generate.py # refresh scrapingrabbit/_methods.py from the live OpenAPI file
|
|
60
|
+
python -m unittest discover -s tests # runs the client against a fake API
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
## License
|
|
64
|
+
|
|
65
|
+
MIT
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["hatchling"]
|
|
3
|
+
build-backend = "hatchling.build"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "scrapingrabbit"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "Python client for the ScrapingRabbit web data API: YouTube transcripts and comments, TikTok, Instagram, X, Amazon, Google and SEO data."
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
license = "MIT"
|
|
11
|
+
requires-python = ">=3.9"
|
|
12
|
+
dependencies = ["httpx>=0.24"]
|
|
13
|
+
keywords = ["scraping", "api", "youtube-transcript", "tiktok", "instagram", "seo", "web-data"]
|
|
14
|
+
classifiers = [
|
|
15
|
+
"Programming Language :: Python :: 3",
|
|
16
|
+
"Operating System :: OS Independent",
|
|
17
|
+
"Typing :: Typed",
|
|
18
|
+
]
|
|
19
|
+
|
|
20
|
+
[project.urls]
|
|
21
|
+
Homepage = "https://scrapingrabbit.com"
|
|
22
|
+
Documentation = "https://scrapingrabbit.com/docs"
|
|
23
|
+
Repository = "https://github.com/pushkarsingh32/scrapingrabbit-python"
|
|
24
|
+
Issues = "https://github.com/pushkarsingh32/scrapingrabbit-python/issues"
|
|
25
|
+
|
|
26
|
+
[tool.hatch.build.targets.wheel]
|
|
27
|
+
packages = ["scrapingrabbit"]
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
"""Python client for the ScrapingRabbit web data API: YouTube, TikTok, Instagram, X, Amazon, Google and SEO data."""
|
|
2
|
+
from .client import AsyncScrapingRabbit, ScrapingRabbit, ScrapingRabbitError
|
|
3
|
+
|
|
4
|
+
__version__ = "0.1.0"
|
|
5
|
+
__all__ = ["ScrapingRabbit", "AsyncScrapingRabbit", "ScrapingRabbitError", "__version__"]
|
|
@@ -0,0 +1,258 @@
|
|
|
1
|
+
"""Generated by scripts/generate.py from https://scrapingrabbit.com/openapi.json. Do not edit by hand."""
|
|
2
|
+
from typing import Any, Optional
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
class SyncMethods:
|
|
6
|
+
"""One method per API endpoint. Needs a `_get(path, query)` method."""
|
|
7
|
+
|
|
8
|
+
def account_credits(self) -> Any:
|
|
9
|
+
"""Your current balance. Free: it does not cost a credit, but it counts toward the rate limit."""
|
|
10
|
+
return self._get("/account/credits", {})
|
|
11
|
+
|
|
12
|
+
def amazon_best_sellers_viewer(self, category_id: str) -> Any:
|
|
13
|
+
"""See the top-selling products in any Amazon category. Costs 1 credit per successful call. Amazon.com only, and the list changes through the day. A wrong category id returns no results."""
|
|
14
|
+
return self._get("/amazon/bestsellers", {"category_id": category_id})
|
|
15
|
+
|
|
16
|
+
def amazon_keyword_tool(self, query: str) -> Any:
|
|
17
|
+
"""See the searches Amazon suggests as shoppers type. Costs 1 credit per successful call. Suggestions show what is popular, not how many searches happen. Results can differ by country and change over time."""
|
|
18
|
+
return self._get("/amazon/autocomplete", {"query": query})
|
|
19
|
+
|
|
20
|
+
def amazon_product_search(self, query: str) -> Any:
|
|
21
|
+
"""Search Amazon and compare products by rating and price. Costs 1 credit per successful call. One page of results per search, from Amazon.com. Prices and stock change often, and some listings show no price."""
|
|
22
|
+
return self._get("/amazon/search", {"query": query})
|
|
23
|
+
|
|
24
|
+
def app_store_reviews_viewer(self, product_id: str) -> Any:
|
|
25
|
+
"""Read what users say about any app on the App Store. Costs 1 credit per successful call. Shows one page of the most helpful reviews from the US store. Reviews are as the store shows them. We do not edit them."""
|
|
26
|
+
return self._get("/apple/reviews", {"product_id": product_id})
|
|
27
|
+
|
|
28
|
+
def app_store_search(self, query: str) -> Any:
|
|
29
|
+
"""Search the App Store and compare apps by rating and price. Costs 1 credit per successful call. Results are from the US App Store. The order is the store's own and changes over time."""
|
|
30
|
+
return self._get("/apple/search", {"query": query})
|
|
31
|
+
|
|
32
|
+
def domain_age_checker(self, domain: str) -> Any:
|
|
33
|
+
"""See when a domain was registered and how old it is. Costs 1 credit per successful call. The date is when the domain was first registered, not when the website launched. Some registries do not publish creation dates, so a few domains return no result."""
|
|
34
|
+
return self._get("/seo/domain-age", {"domain": domain})
|
|
35
|
+
|
|
36
|
+
def domain_authority_checker(self, domain: str) -> Any:
|
|
37
|
+
"""See a website's Moz Domain Authority, Page Authority and spam score. Costs 1 credit per successful call. Domain Authority is a Moz score. It is a rough guide to link strength, not a Google ranking factor. Scores move as Moz updates its index, so compare sites on the same day. A new site with few links usually scores low even if its content is good."""
|
|
38
|
+
return self._get("/seo/domain-authority", {"domain": domain})
|
|
39
|
+
|
|
40
|
+
def email_verifier(self, email: str) -> Any:
|
|
41
|
+
"""Check the format, mail servers and type of any email address. Costs 1 credit per successful call. This checks the format and the domain's mail setup. It does not connect to the mailbox, so it cannot prove a specific inbox exists. Catch-all domains accept every address, so a valid result there is not a guarantee."""
|
|
42
|
+
return self._get("/email/verify", {"email": email})
|
|
43
|
+
|
|
44
|
+
def google_autocomplete(self, query: str) -> Any:
|
|
45
|
+
"""See the searches Google suggests as people type. Costs 1 credit per successful call. Suggestions are not search volumes. They show what is popular, not how many searches happen. Results can differ by country, language and time."""
|
|
46
|
+
return self._get("/google/autocomplete", {"query": query})
|
|
47
|
+
|
|
48
|
+
def google_maps_business_search(self, query: str) -> Any:
|
|
49
|
+
"""Find local businesses with their ratings, phone numbers and websites. Costs 5 credits per successful call. Each search returns one page of results, around 20 businesses. Phone numbers and websites appear only where the business published them."""
|
|
50
|
+
return self._get("/google/maps", {"query": query})
|
|
51
|
+
|
|
52
|
+
def google_news_search(self, query: str) -> Any:
|
|
53
|
+
"""Get the latest headlines on any topic from Google News. Costs 5 credits per successful call. Headlines come from Google News and link to the publisher's own page. Results change often, so the list can differ from one hour to the next."""
|
|
54
|
+
return self._get("/google/news", {"query": query})
|
|
55
|
+
|
|
56
|
+
def google_trends_explorer(self, query: str) -> Any:
|
|
57
|
+
"""See how interest in a search term moved over the past year. Costs 5 credits per successful call. Values are relative on a 0 to 100 scale, where 100 is the term's own peak. They are not search counts. Very rare terms may have too little data to chart."""
|
|
58
|
+
return self._get("/google/trends", {"query": query})
|
|
59
|
+
|
|
60
|
+
def instagram_highlight_viewer(self, username: str) -> Any:
|
|
61
|
+
"""Browse a profile's Instagram highlights and the stories inside them. Costs 5 credits per successful call. Photo and video links come from Instagram's own servers and may stop working after a while, so open them while you need them. A private account may show no highlights."""
|
|
62
|
+
return self._get("/instagram/highlights", {"username": username})
|
|
63
|
+
|
|
64
|
+
def instagram_profile_viewer(self, username: str) -> Any:
|
|
65
|
+
"""View the public stats, bio and links of an Instagram profile. Costs 5 credits per successful call. Only public information is returned. Private accounts show their public header only. Counts are a snapshot and can differ slightly from the app."""
|
|
66
|
+
return self._get("/instagram/profile", {"username": username})
|
|
67
|
+
|
|
68
|
+
def instagram_username_checker(self, username: str) -> Any:
|
|
69
|
+
"""See if an Instagram username is free, or who has it. Costs 5 credits per successful call. Results come from public Instagram data at the time of the search. A name shown as available can still be blocked by Instagram at sign-up."""
|
|
70
|
+
return self._get("/instagram/username/check", {"username": username})
|
|
71
|
+
|
|
72
|
+
def snapchat_profile_viewer(self, username: str) -> Any:
|
|
73
|
+
"""See a public Snapchat profile without an account. Costs 5 credits per successful call. Only public profiles can be read. Private accounts show no data. Subscriber counts shown are the ones Snapchat publishes on the profile."""
|
|
74
|
+
return self._get("/snapchat/profile", {"username": username})
|
|
75
|
+
|
|
76
|
+
def tiktok_engagement_rate_calculator(self, username: str) -> Any:
|
|
77
|
+
"""See an account's engagement rate from its recent videos. Costs 5 credits per successful call. The rate uses only the latest 10 videos, so a recent viral or flop video moves it a lot. Very large accounts often have a low rate by followers but a high rate by views, so read both numbers. Only public data is used."""
|
|
78
|
+
return self._get("/tiktok/engagement", {"username": username})
|
|
79
|
+
|
|
80
|
+
def tiktok_profile_viewer(self, username: str) -> Any:
|
|
81
|
+
"""View the public stats, bio and link of a TikTok profile. Costs 5 credits per successful call. Only public information is returned. Counts are a snapshot and can differ slightly from the app."""
|
|
82
|
+
return self._get("/tiktok/profile", {"username": username})
|
|
83
|
+
|
|
84
|
+
def tiktok_transcript(self, url: str) -> Any:
|
|
85
|
+
"""Get the spoken words of any TikTok video as text. Costs 5 credits per successful call. A transcript exists only when TikTok has captions for the video. Videos with no speech or no captions return nothing. Auto-generated captions can contain mistakes. Photo posts and private videos have no transcript."""
|
|
86
|
+
return self._get("/tiktok/transcript", {"url": url})
|
|
87
|
+
|
|
88
|
+
def tiktok_username_checker(self, username: str) -> Any:
|
|
89
|
+
"""See if a TikTok username is free, or who has it. Costs 5 credits per successful call. Results come from public TikTok data at the time of the search. A name shown as available can still be blocked by TikTok at sign-up."""
|
|
90
|
+
return self._get("/tiktok/username/check", {"username": username})
|
|
91
|
+
|
|
92
|
+
def walmart_keyword_tool(self, query: str) -> Any:
|
|
93
|
+
"""See the searches Walmart suggests as shoppers type. Costs 1 credit per successful call. Suggestions show what is popular, not how many searches happen. Results can differ over time."""
|
|
94
|
+
return self._get("/walmart/autocomplete", {"query": query})
|
|
95
|
+
|
|
96
|
+
def walmart_product_search(self, query: str) -> Any:
|
|
97
|
+
"""Search Walmart and compare products by price and rating. Costs 1 credit per successful call. One page of results per search. Prices and stock change often, and some listings show a price range or no price. Walmart sometimes blocks a lookup. If you see an error, try again."""
|
|
98
|
+
return self._get("/walmart/search", {"query": query})
|
|
99
|
+
|
|
100
|
+
def website_traffic_checker(self, domain: str) -> Any:
|
|
101
|
+
"""Estimate a site's organic search traffic and ranking keywords. Costs 1 credit per successful call. These are estimates built from the keywords a site ranks for. They are not the site's own analytics. Brand-new sites and very small sites often show no data."""
|
|
102
|
+
return self._get("/seo/website-traffic", {"domain": domain})
|
|
103
|
+
|
|
104
|
+
def x_video_transcript(self, url: str) -> Any:
|
|
105
|
+
"""Get the spoken words of any X video as text. Costs 5 credits per successful call. A transcript exists only when X has captions for the video. Many videos have none. Auto-generated captions can contain mistakes. Posts without a video, and private accounts, have no transcript."""
|
|
106
|
+
return self._get("/twitter/transcript", {"url": url})
|
|
107
|
+
|
|
108
|
+
def youtube_banner_downloader(self, channel_id: str) -> Any:
|
|
109
|
+
"""Get a channel's full-size banner and profile picture. Costs 1 credit per successful call. Channels without a banner show only the profile picture. Images belong to the channel owner. Use them only as the owner allows."""
|
|
110
|
+
return self._get("/youtube/channel/banner", {"channel_id": channel_id})
|
|
111
|
+
|
|
112
|
+
def youtube_channel_id_finder(self, handle: str) -> Any:
|
|
113
|
+
"""Turn a YouTube @handle into the channel ID. Costs 1 credit per successful call. Needs a channel handle (starting with @) or a link that contains one. Channels that have no handle cannot be looked up this way."""
|
|
114
|
+
return self._get("/youtube/resolve", {"handle": handle})
|
|
115
|
+
|
|
116
|
+
def youtube_channel_viewer(self, channel_id: str) -> Any:
|
|
117
|
+
"""See a channel's subscribers, views, video count and links. Costs 1 credit per successful call. Only public information is returned. Hidden subscriber counts show as unavailable. YouTube rounds large counts, so figures are close but not exact."""
|
|
118
|
+
return self._get("/youtube/channel", {"channel_id": channel_id})
|
|
119
|
+
|
|
120
|
+
def youtube_comment_extractor(self, url: str, next_page_token: Optional[str] = None) -> Any:
|
|
121
|
+
"""Read the top comments of any YouTube video with likes and replies. Costs 1 credit per successful call. This page shows the first page of top comments, not every comment on the video. Videos with comments turned off return nothing."""
|
|
122
|
+
return self._get("/youtube/comments", {"url": url, "next_page_token": next_page_token})
|
|
123
|
+
|
|
124
|
+
def youtube_tag_extractor(self, url: str) -> Any:
|
|
125
|
+
"""See the tags and keywords any YouTube video uses. Costs 1 credit per successful call. Tags are only shown when the creator added them. Many videos have none. Tags are a small signal for YouTube search. Title, description and viewer behavior matter far more."""
|
|
126
|
+
return self._get("/youtube/video", {"url": url})
|
|
127
|
+
|
|
128
|
+
def youtube_transcript(self, url: str) -> Any:
|
|
129
|
+
"""Convert any YouTube video to a transcript with timestamps. Costs 1 credit per successful call. A transcript exists only when the video has captions, written by the creator or generated by YouTube. Private videos and videos with captions turned off return no transcript. Auto-generated captions can contain mistakes, especially with names and technical terms."""
|
|
130
|
+
return self._get("/youtube/transcript", {"url": url})
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
class AsyncMethods:
|
|
134
|
+
"""The same methods, awaitable. Needs an async `_get(path, query)` method."""
|
|
135
|
+
|
|
136
|
+
async def account_credits(self) -> Any:
|
|
137
|
+
"""Your current balance. Free: it does not cost a credit, but it counts toward the rate limit."""
|
|
138
|
+
return await self._get("/account/credits", {})
|
|
139
|
+
|
|
140
|
+
async def amazon_best_sellers_viewer(self, category_id: str) -> Any:
|
|
141
|
+
"""See the top-selling products in any Amazon category. Costs 1 credit per successful call. Amazon.com only, and the list changes through the day. A wrong category id returns no results."""
|
|
142
|
+
return await self._get("/amazon/bestsellers", {"category_id": category_id})
|
|
143
|
+
|
|
144
|
+
async def amazon_keyword_tool(self, query: str) -> Any:
|
|
145
|
+
"""See the searches Amazon suggests as shoppers type. Costs 1 credit per successful call. Suggestions show what is popular, not how many searches happen. Results can differ by country and change over time."""
|
|
146
|
+
return await self._get("/amazon/autocomplete", {"query": query})
|
|
147
|
+
|
|
148
|
+
async def amazon_product_search(self, query: str) -> Any:
|
|
149
|
+
"""Search Amazon and compare products by rating and price. Costs 1 credit per successful call. One page of results per search, from Amazon.com. Prices and stock change often, and some listings show no price."""
|
|
150
|
+
return await self._get("/amazon/search", {"query": query})
|
|
151
|
+
|
|
152
|
+
async def app_store_reviews_viewer(self, product_id: str) -> Any:
|
|
153
|
+
"""Read what users say about any app on the App Store. Costs 1 credit per successful call. Shows one page of the most helpful reviews from the US store. Reviews are as the store shows them. We do not edit them."""
|
|
154
|
+
return await self._get("/apple/reviews", {"product_id": product_id})
|
|
155
|
+
|
|
156
|
+
async def app_store_search(self, query: str) -> Any:
|
|
157
|
+
"""Search the App Store and compare apps by rating and price. Costs 1 credit per successful call. Results are from the US App Store. The order is the store's own and changes over time."""
|
|
158
|
+
return await self._get("/apple/search", {"query": query})
|
|
159
|
+
|
|
160
|
+
async def domain_age_checker(self, domain: str) -> Any:
|
|
161
|
+
"""See when a domain was registered and how old it is. Costs 1 credit per successful call. The date is when the domain was first registered, not when the website launched. Some registries do not publish creation dates, so a few domains return no result."""
|
|
162
|
+
return await self._get("/seo/domain-age", {"domain": domain})
|
|
163
|
+
|
|
164
|
+
async def domain_authority_checker(self, domain: str) -> Any:
|
|
165
|
+
"""See a website's Moz Domain Authority, Page Authority and spam score. Costs 1 credit per successful call. Domain Authority is a Moz score. It is a rough guide to link strength, not a Google ranking factor. Scores move as Moz updates its index, so compare sites on the same day. A new site with few links usually scores low even if its content is good."""
|
|
166
|
+
return await self._get("/seo/domain-authority", {"domain": domain})
|
|
167
|
+
|
|
168
|
+
async def email_verifier(self, email: str) -> Any:
|
|
169
|
+
"""Check the format, mail servers and type of any email address. Costs 1 credit per successful call. This checks the format and the domain's mail setup. It does not connect to the mailbox, so it cannot prove a specific inbox exists. Catch-all domains accept every address, so a valid result there is not a guarantee."""
|
|
170
|
+
return await self._get("/email/verify", {"email": email})
|
|
171
|
+
|
|
172
|
+
async def google_autocomplete(self, query: str) -> Any:
|
|
173
|
+
"""See the searches Google suggests as people type. Costs 1 credit per successful call. Suggestions are not search volumes. They show what is popular, not how many searches happen. Results can differ by country, language and time."""
|
|
174
|
+
return await self._get("/google/autocomplete", {"query": query})
|
|
175
|
+
|
|
176
|
+
async def google_maps_business_search(self, query: str) -> Any:
|
|
177
|
+
"""Find local businesses with their ratings, phone numbers and websites. Costs 5 credits per successful call. Each search returns one page of results, around 20 businesses. Phone numbers and websites appear only where the business published them."""
|
|
178
|
+
return await self._get("/google/maps", {"query": query})
|
|
179
|
+
|
|
180
|
+
async def google_news_search(self, query: str) -> Any:
|
|
181
|
+
"""Get the latest headlines on any topic from Google News. Costs 5 credits per successful call. Headlines come from Google News and link to the publisher's own page. Results change often, so the list can differ from one hour to the next."""
|
|
182
|
+
return await self._get("/google/news", {"query": query})
|
|
183
|
+
|
|
184
|
+
async def google_trends_explorer(self, query: str) -> Any:
|
|
185
|
+
"""See how interest in a search term moved over the past year. Costs 5 credits per successful call. Values are relative on a 0 to 100 scale, where 100 is the term's own peak. They are not search counts. Very rare terms may have too little data to chart."""
|
|
186
|
+
return await self._get("/google/trends", {"query": query})
|
|
187
|
+
|
|
188
|
+
async def instagram_highlight_viewer(self, username: str) -> Any:
|
|
189
|
+
"""Browse a profile's Instagram highlights and the stories inside them. Costs 5 credits per successful call. Photo and video links come from Instagram's own servers and may stop working after a while, so open them while you need them. A private account may show no highlights."""
|
|
190
|
+
return await self._get("/instagram/highlights", {"username": username})
|
|
191
|
+
|
|
192
|
+
async def instagram_profile_viewer(self, username: str) -> Any:
|
|
193
|
+
"""View the public stats, bio and links of an Instagram profile. Costs 5 credits per successful call. Only public information is returned. Private accounts show their public header only. Counts are a snapshot and can differ slightly from the app."""
|
|
194
|
+
return await self._get("/instagram/profile", {"username": username})
|
|
195
|
+
|
|
196
|
+
async def instagram_username_checker(self, username: str) -> Any:
|
|
197
|
+
"""See if an Instagram username is free, or who has it. Costs 5 credits per successful call. Results come from public Instagram data at the time of the search. A name shown as available can still be blocked by Instagram at sign-up."""
|
|
198
|
+
return await self._get("/instagram/username/check", {"username": username})
|
|
199
|
+
|
|
200
|
+
async def snapchat_profile_viewer(self, username: str) -> Any:
|
|
201
|
+
"""See a public Snapchat profile without an account. Costs 5 credits per successful call. Only public profiles can be read. Private accounts show no data. Subscriber counts shown are the ones Snapchat publishes on the profile."""
|
|
202
|
+
return await self._get("/snapchat/profile", {"username": username})
|
|
203
|
+
|
|
204
|
+
async def tiktok_engagement_rate_calculator(self, username: str) -> Any:
|
|
205
|
+
"""See an account's engagement rate from its recent videos. Costs 5 credits per successful call. The rate uses only the latest 10 videos, so a recent viral or flop video moves it a lot. Very large accounts often have a low rate by followers but a high rate by views, so read both numbers. Only public data is used."""
|
|
206
|
+
return await self._get("/tiktok/engagement", {"username": username})
|
|
207
|
+
|
|
208
|
+
async def tiktok_profile_viewer(self, username: str) -> Any:
|
|
209
|
+
"""View the public stats, bio and link of a TikTok profile. Costs 5 credits per successful call. Only public information is returned. Counts are a snapshot and can differ slightly from the app."""
|
|
210
|
+
return await self._get("/tiktok/profile", {"username": username})
|
|
211
|
+
|
|
212
|
+
async def tiktok_transcript(self, url: str) -> Any:
|
|
213
|
+
"""Get the spoken words of any TikTok video as text. Costs 5 credits per successful call. A transcript exists only when TikTok has captions for the video. Videos with no speech or no captions return nothing. Auto-generated captions can contain mistakes. Photo posts and private videos have no transcript."""
|
|
214
|
+
return await self._get("/tiktok/transcript", {"url": url})
|
|
215
|
+
|
|
216
|
+
async def tiktok_username_checker(self, username: str) -> Any:
|
|
217
|
+
"""See if a TikTok username is free, or who has it. Costs 5 credits per successful call. Results come from public TikTok data at the time of the search. A name shown as available can still be blocked by TikTok at sign-up."""
|
|
218
|
+
return await self._get("/tiktok/username/check", {"username": username})
|
|
219
|
+
|
|
220
|
+
async def walmart_keyword_tool(self, query: str) -> Any:
|
|
221
|
+
"""See the searches Walmart suggests as shoppers type. Costs 1 credit per successful call. Suggestions show what is popular, not how many searches happen. Results can differ over time."""
|
|
222
|
+
return await self._get("/walmart/autocomplete", {"query": query})
|
|
223
|
+
|
|
224
|
+
async def walmart_product_search(self, query: str) -> Any:
|
|
225
|
+
"""Search Walmart and compare products by price and rating. Costs 1 credit per successful call. One page of results per search. Prices and stock change often, and some listings show a price range or no price. Walmart sometimes blocks a lookup. If you see an error, try again."""
|
|
226
|
+
return await self._get("/walmart/search", {"query": query})
|
|
227
|
+
|
|
228
|
+
async def website_traffic_checker(self, domain: str) -> Any:
|
|
229
|
+
"""Estimate a site's organic search traffic and ranking keywords. Costs 1 credit per successful call. These are estimates built from the keywords a site ranks for. They are not the site's own analytics. Brand-new sites and very small sites often show no data."""
|
|
230
|
+
return await self._get("/seo/website-traffic", {"domain": domain})
|
|
231
|
+
|
|
232
|
+
async def x_video_transcript(self, url: str) -> Any:
|
|
233
|
+
"""Get the spoken words of any X video as text. Costs 5 credits per successful call. A transcript exists only when X has captions for the video. Many videos have none. Auto-generated captions can contain mistakes. Posts without a video, and private accounts, have no transcript."""
|
|
234
|
+
return await self._get("/twitter/transcript", {"url": url})
|
|
235
|
+
|
|
236
|
+
async def youtube_banner_downloader(self, channel_id: str) -> Any:
|
|
237
|
+
"""Get a channel's full-size banner and profile picture. Costs 1 credit per successful call. Channels without a banner show only the profile picture. Images belong to the channel owner. Use them only as the owner allows."""
|
|
238
|
+
return await self._get("/youtube/channel/banner", {"channel_id": channel_id})
|
|
239
|
+
|
|
240
|
+
async def youtube_channel_id_finder(self, handle: str) -> Any:
|
|
241
|
+
"""Turn a YouTube @handle into the channel ID. Costs 1 credit per successful call. Needs a channel handle (starting with @) or a link that contains one. Channels that have no handle cannot be looked up this way."""
|
|
242
|
+
return await self._get("/youtube/resolve", {"handle": handle})
|
|
243
|
+
|
|
244
|
+
async def youtube_channel_viewer(self, channel_id: str) -> Any:
|
|
245
|
+
"""See a channel's subscribers, views, video count and links. Costs 1 credit per successful call. Only public information is returned. Hidden subscriber counts show as unavailable. YouTube rounds large counts, so figures are close but not exact."""
|
|
246
|
+
return await self._get("/youtube/channel", {"channel_id": channel_id})
|
|
247
|
+
|
|
248
|
+
async def youtube_comment_extractor(self, url: str, next_page_token: Optional[str] = None) -> Any:
|
|
249
|
+
"""Read the top comments of any YouTube video with likes and replies. Costs 1 credit per successful call. This page shows the first page of top comments, not every comment on the video. Videos with comments turned off return nothing."""
|
|
250
|
+
return await self._get("/youtube/comments", {"url": url, "next_page_token": next_page_token})
|
|
251
|
+
|
|
252
|
+
async def youtube_tag_extractor(self, url: str) -> Any:
|
|
253
|
+
"""See the tags and keywords any YouTube video uses. Costs 1 credit per successful call. Tags are only shown when the creator added them. Many videos have none. Tags are a small signal for YouTube search. Title, description and viewer behavior matter far more."""
|
|
254
|
+
return await self._get("/youtube/video", {"url": url})
|
|
255
|
+
|
|
256
|
+
async def youtube_transcript(self, url: str) -> Any:
|
|
257
|
+
"""Convert any YouTube video to a transcript with timestamps. Costs 1 credit per successful call. A transcript exists only when the video has captions, written by the creator or generated by YouTube. Private videos and videos with captions turned off return no transcript. Auto-generated captions can contain mistakes, especially with names and technical terms."""
|
|
258
|
+
return await self._get("/youtube/transcript", {"url": url})
|
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
"""The ScrapingRabbit clients (sync and async). Methods for each endpoint are in _methods.py (generated)."""
|
|
2
|
+
import asyncio
|
|
3
|
+
import json
|
|
4
|
+
import os
|
|
5
|
+
import time
|
|
6
|
+
from typing import Any, Dict, Optional
|
|
7
|
+
|
|
8
|
+
import httpx
|
|
9
|
+
|
|
10
|
+
from ._methods import AsyncMethods, SyncMethods
|
|
11
|
+
|
|
12
|
+
DEFAULT_BASE_URL = "https://api.scrapingrabbit.com/v1"
|
|
13
|
+
_MAX_WAIT_SECONDS = 30.0
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class ScrapingRabbitError(Exception):
|
|
17
|
+
"""The API refused or failed a call. Failed calls are not charged."""
|
|
18
|
+
|
|
19
|
+
def __init__(self, message: str, code: str = "UNKNOWN", status: Optional[int] = None, retry_after: Optional[float] = None):
|
|
20
|
+
super().__init__(f"{code}: {message}")
|
|
21
|
+
self.message = message
|
|
22
|
+
self.code = code
|
|
23
|
+
self.status = status
|
|
24
|
+
self.retry_after = retry_after
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def _resolve_key(api_key: Optional[str]) -> str:
|
|
28
|
+
key = api_key or os.environ.get("SCRAPINGRABBIT_API_KEY")
|
|
29
|
+
if not key:
|
|
30
|
+
raise ScrapingRabbitError(
|
|
31
|
+
"No API key. Pass api_key=... or set SCRAPINGRABBIT_API_KEY. Get a free key (100 credits, no card) at https://scrapingrabbit.com/login",
|
|
32
|
+
code="MISSING_API_KEY",
|
|
33
|
+
)
|
|
34
|
+
return key
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def _clean(query: Dict[str, Optional[str]]) -> Dict[str, str]:
|
|
38
|
+
return {name: str(value) for name, value in query.items() if value not in (None, "")}
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def _unwrap(response: httpx.Response) -> Any:
|
|
42
|
+
"""The `data` of a successful answer, or a ScrapingRabbitError."""
|
|
43
|
+
try:
|
|
44
|
+
body = response.json()
|
|
45
|
+
except (json.JSONDecodeError, ValueError):
|
|
46
|
+
body = None
|
|
47
|
+
if response.is_success and isinstance(body, dict) and body.get("success") is not False:
|
|
48
|
+
return body.get("data", body)
|
|
49
|
+
retry_header = response.headers.get("retry-after")
|
|
50
|
+
retry_after = float(retry_header) if retry_header and retry_header.replace(".", "", 1).isdigit() else None
|
|
51
|
+
if isinstance(body, dict):
|
|
52
|
+
raise ScrapingRabbitError(str(body.get("message", f"HTTP {response.status_code}")), str(body.get("code", "UNKNOWN")), response.status_code, retry_after)
|
|
53
|
+
raise ScrapingRabbitError(f"HTTP {response.status_code}", "UNKNOWN", response.status_code, retry_after)
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def _wait_for(error: ScrapingRabbitError, attempt: int) -> Optional[float]:
|
|
57
|
+
"""Seconds to wait before retrying, or None to give up. Only rate limits and server errors are retried."""
|
|
58
|
+
if error.status == 429:
|
|
59
|
+
return min(error.retry_after if error.retry_after is not None else 2.0 ** attempt, _MAX_WAIT_SECONDS)
|
|
60
|
+
if error.status is not None and error.status >= 500:
|
|
61
|
+
return min(2.0 ** attempt, _MAX_WAIT_SECONDS)
|
|
62
|
+
return None
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
class ScrapingRabbit(SyncMethods):
|
|
66
|
+
"""Blocking client. `ScrapingRabbit(api_key).youtube_transcript(url=...)` returns the answer's `data`."""
|
|
67
|
+
|
|
68
|
+
def __init__(self, api_key: Optional[str] = None, base_url: str = DEFAULT_BASE_URL, timeout: float = 60.0, max_retries: int = 2):
|
|
69
|
+
self._max_retries = max_retries
|
|
70
|
+
self._http = httpx.Client(base_url=base_url.rstrip("/"), timeout=timeout, headers={"x-api-key": _resolve_key(api_key)})
|
|
71
|
+
|
|
72
|
+
def _get(self, path: str, query: Dict[str, Optional[str]]) -> Any:
|
|
73
|
+
# Retrying is safe: a call is charged only when it succeeds.
|
|
74
|
+
for attempt in range(self._max_retries + 1):
|
|
75
|
+
try:
|
|
76
|
+
return _unwrap(self._http.get(path, params=_clean(query)))
|
|
77
|
+
except ScrapingRabbitError as error:
|
|
78
|
+
wait = _wait_for(error, attempt)
|
|
79
|
+
if wait is None or attempt == self._max_retries:
|
|
80
|
+
raise
|
|
81
|
+
time.sleep(wait)
|
|
82
|
+
except httpx.TransportError as error:
|
|
83
|
+
if attempt == self._max_retries:
|
|
84
|
+
raise ScrapingRabbitError(f"Could not reach the API: {error}", "NETWORK_ERROR") from error
|
|
85
|
+
time.sleep(min(2.0 ** attempt, _MAX_WAIT_SECONDS))
|
|
86
|
+
raise AssertionError("unreachable")
|
|
87
|
+
|
|
88
|
+
def close(self) -> None:
|
|
89
|
+
self._http.close()
|
|
90
|
+
|
|
91
|
+
def __enter__(self) -> "ScrapingRabbit":
|
|
92
|
+
return self
|
|
93
|
+
|
|
94
|
+
def __exit__(self, *exc: object) -> None:
|
|
95
|
+
self.close()
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
class AsyncScrapingRabbit(AsyncMethods):
|
|
99
|
+
"""Awaitable client with the same methods: `await client.youtube_transcript(url=...)`."""
|
|
100
|
+
|
|
101
|
+
def __init__(self, api_key: Optional[str] = None, base_url: str = DEFAULT_BASE_URL, timeout: float = 60.0, max_retries: int = 2):
|
|
102
|
+
self._max_retries = max_retries
|
|
103
|
+
self._http = httpx.AsyncClient(base_url=base_url.rstrip("/"), timeout=timeout, headers={"x-api-key": _resolve_key(api_key)})
|
|
104
|
+
|
|
105
|
+
async def _get(self, path: str, query: Dict[str, Optional[str]]) -> Any:
|
|
106
|
+
for attempt in range(self._max_retries + 1):
|
|
107
|
+
try:
|
|
108
|
+
return _unwrap(await self._http.get(path, params=_clean(query)))
|
|
109
|
+
except ScrapingRabbitError as error:
|
|
110
|
+
wait = _wait_for(error, attempt)
|
|
111
|
+
if wait is None or attempt == self._max_retries:
|
|
112
|
+
raise
|
|
113
|
+
await asyncio.sleep(wait)
|
|
114
|
+
except httpx.TransportError as error:
|
|
115
|
+
if attempt == self._max_retries:
|
|
116
|
+
raise ScrapingRabbitError(f"Could not reach the API: {error}", "NETWORK_ERROR") from error
|
|
117
|
+
await asyncio.sleep(min(2.0 ** attempt, _MAX_WAIT_SECONDS))
|
|
118
|
+
raise AssertionError("unreachable")
|
|
119
|
+
|
|
120
|
+
async def aclose(self) -> None:
|
|
121
|
+
await self._http.aclose()
|
|
122
|
+
|
|
123
|
+
async def __aenter__(self) -> "AsyncScrapingRabbit":
|
|
124
|
+
return self
|
|
125
|
+
|
|
126
|
+
async def __aexit__(self, *exc: object) -> None:
|
|
127
|
+
await self.aclose()
|
|
File without changes
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
"""Run: python scripts/generate.py
|
|
2
|
+
|
|
3
|
+
Writes scrapingrabbit/_methods.py from the live OpenAPI file, so the client has exactly the endpoints the API has
|
|
4
|
+
(one source of truth: https://scrapingrabbit.com/openapi.json). Commit the result.
|
|
5
|
+
"""
|
|
6
|
+
import json
|
|
7
|
+
import os
|
|
8
|
+
import re
|
|
9
|
+
import urllib.request
|
|
10
|
+
|
|
11
|
+
SPEC_URL = os.environ.get("SCRAPINGRABBIT_SPEC_URL", "https://scrapingrabbit.com/openapi.json")
|
|
12
|
+
OUT = os.path.join(os.path.dirname(__file__), "..", "scrapingrabbit", "_methods.py")
|
|
13
|
+
|
|
14
|
+
with urllib.request.urlopen(SPEC_URL, timeout=30) as response:
|
|
15
|
+
spec = json.load(response)
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def snake(name: str) -> str:
|
|
19
|
+
return re.sub(r"([a-z0-9])([A-Z])", r"\1_\2", name).lower()
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
endpoints = []
|
|
23
|
+
for path, item in spec["paths"].items():
|
|
24
|
+
operation = item.get("get")
|
|
25
|
+
if not operation:
|
|
26
|
+
continue
|
|
27
|
+
params = [p for p in operation.get("parameters", []) if p.get("in") == "query"]
|
|
28
|
+
endpoints.append(
|
|
29
|
+
{
|
|
30
|
+
"name": snake(operation["operationId"]),
|
|
31
|
+
"path": path,
|
|
32
|
+
"summary": operation.get("summary", ""),
|
|
33
|
+
"description": operation.get("description", ""),
|
|
34
|
+
"credits": operation.get("x-credits", 0),
|
|
35
|
+
"params": [{"name": p["name"], "required": bool(p.get("required")), "doc": p.get("description", "")} for p in params],
|
|
36
|
+
}
|
|
37
|
+
)
|
|
38
|
+
endpoints.sort(key=lambda e: e["name"])
|
|
39
|
+
if len({e["name"] for e in endpoints}) != len(endpoints):
|
|
40
|
+
raise SystemExit("Two endpoints produce the same method name")
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def signature(endpoint, is_async: bool) -> str:
|
|
44
|
+
required = [p["name"] for p in endpoint["params"] if p["required"]]
|
|
45
|
+
optional = [f'{p["name"]}: Optional[str] = None' for p in endpoint["params"] if not p["required"]]
|
|
46
|
+
args = ", ".join(["self"] + [f"{name}: str" for name in required] + optional)
|
|
47
|
+
return f' {"async " if is_async else ""}def {endpoint["name"]}({args}) -> Any:'
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def method(endpoint, is_async: bool) -> str:
|
|
51
|
+
doc = endpoint["description"].replace('"""', "'''") # the description already states the cost
|
|
52
|
+
names = [p["name"] for p in endpoint["params"]]
|
|
53
|
+
query = "{" + ", ".join(f'"{n}": {n}' for n in names) + "}"
|
|
54
|
+
call = f'self._get("{endpoint["path"]}", {query})'
|
|
55
|
+
return f'{signature(endpoint, is_async)}\n """{doc}"""\n return {"await " if is_async else ""}{call}\n'
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
header = f'''"""Generated by scripts/generate.py from {SPEC_URL}. Do not edit by hand."""
|
|
59
|
+
from typing import Any, Optional
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
'''
|
|
63
|
+
body = header + "class SyncMethods:\n \"\"\"One method per API endpoint. Needs a `_get(path, query)` method.\"\"\"\n\n" + "\n".join(method(e, False) for e in endpoints)
|
|
64
|
+
body += "\n\nclass AsyncMethods:\n \"\"\"The same methods, awaitable. Needs an async `_get(path, query)` method.\"\"\"\n\n" + "\n".join(method(e, True) for e in endpoints)
|
|
65
|
+
with open(OUT, "w") as f:
|
|
66
|
+
f.write(body)
|
|
67
|
+
print(f"wrote {len(endpoints)} methods")
|
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
"""Run: python -m unittest discover -s tests
|
|
2
|
+
|
|
3
|
+
Runs the real client against a fake API on a local port. Checks that the key goes in the header (never the URL), that
|
|
4
|
+
parameters reach the API, that errors carry their code, and that rate limits are retried but other refusals are not.
|
|
5
|
+
"""
|
|
6
|
+
import asyncio
|
|
7
|
+
import json
|
|
8
|
+
import threading
|
|
9
|
+
import unittest
|
|
10
|
+
from http.server import BaseHTTPRequestHandler, HTTPServer
|
|
11
|
+
|
|
12
|
+
from scrapingrabbit import AsyncScrapingRabbit, ScrapingRabbit, ScrapingRabbitError
|
|
13
|
+
|
|
14
|
+
SEEN = []
|
|
15
|
+
LIMIT_LEFT = [0]
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class Handler(BaseHTTPRequestHandler):
|
|
19
|
+
def log_message(self, *args):
|
|
20
|
+
pass
|
|
21
|
+
|
|
22
|
+
def do_GET(self):
|
|
23
|
+
SEEN.append({"path": self.path, "key": self.headers.get("x-api-key")})
|
|
24
|
+
status, headers, body = 200, {}, {"success": True, "data": {"echo": self.path}}
|
|
25
|
+
if "missing" in self.path:
|
|
26
|
+
status, body = 404, {"success": False, "code": "UPSTREAM_NOT_FOUND", "message": "That video is no longer available."}
|
|
27
|
+
elif "limited" in self.path and LIMIT_LEFT[0] > 0:
|
|
28
|
+
LIMIT_LEFT[0] -= 1
|
|
29
|
+
status, headers, body = 429, {"Retry-After": "0"}, {"success": False, "code": "RATE_LIMITED", "message": "Slow down."}
|
|
30
|
+
payload = json.dumps(body).encode()
|
|
31
|
+
self.send_response(status)
|
|
32
|
+
self.send_header("content-type", "application/json")
|
|
33
|
+
for name, value in headers.items():
|
|
34
|
+
self.send_header(name, value)
|
|
35
|
+
self.send_header("content-length", str(len(payload)))
|
|
36
|
+
self.end_headers()
|
|
37
|
+
self.wfile.write(payload)
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
class ClientTests(unittest.TestCase):
|
|
41
|
+
@classmethod
|
|
42
|
+
def setUpClass(cls):
|
|
43
|
+
cls.server = HTTPServer(("127.0.0.1", 0), Handler)
|
|
44
|
+
cls.url = f"http://127.0.0.1:{cls.server.server_port}/v1"
|
|
45
|
+
threading.Thread(target=cls.server.serve_forever, daemon=True).start()
|
|
46
|
+
|
|
47
|
+
@classmethod
|
|
48
|
+
def tearDownClass(cls):
|
|
49
|
+
cls.server.shutdown()
|
|
50
|
+
|
|
51
|
+
def setUp(self):
|
|
52
|
+
SEEN.clear()
|
|
53
|
+
self.client = ScrapingRabbit("sr_live_testkey", base_url=self.url)
|
|
54
|
+
|
|
55
|
+
def test_key_in_header_params_in_query_and_data_returned(self):
|
|
56
|
+
data = self.client.youtube_transcript(url="https://www.youtube.com/watch?v=dQw4w9WgXcQ")
|
|
57
|
+
self.assertTrue(data["echo"].startswith("/v1/youtube/transcript?url=https%3A%2F%2Fwww.youtube.com"))
|
|
58
|
+
self.assertEqual(SEEN[-1]["key"], "sr_live_testkey")
|
|
59
|
+
self.assertNotIn("sr_live_testkey", SEEN[-1]["path"])
|
|
60
|
+
|
|
61
|
+
def test_optional_parameter_is_sent_only_when_given(self):
|
|
62
|
+
self.client.youtube_comment_extractor(url="abc")
|
|
63
|
+
self.assertNotIn("next_page_token", SEEN[-1]["path"])
|
|
64
|
+
self.client.youtube_comment_extractor(url="abc", next_page_token="tok%3D")
|
|
65
|
+
self.assertIn("next_page_token=tok%253D", SEEN[-1]["path"])
|
|
66
|
+
|
|
67
|
+
def test_api_refusal_raises_with_code_and_is_not_retried(self):
|
|
68
|
+
with self.assertRaises(ScrapingRabbitError) as caught:
|
|
69
|
+
self.client.youtube_transcript(url="missing0000")
|
|
70
|
+
self.assertEqual(caught.exception.code, "UPSTREAM_NOT_FOUND")
|
|
71
|
+
self.assertEqual(caught.exception.status, 404)
|
|
72
|
+
self.assertEqual(len(SEEN), 1)
|
|
73
|
+
|
|
74
|
+
def test_rate_limit_is_retried_then_succeeds(self):
|
|
75
|
+
LIMIT_LEFT[0] = 2
|
|
76
|
+
data = self.client.youtube_transcript(url="limited")
|
|
77
|
+
self.assertIn("echo", data)
|
|
78
|
+
self.assertEqual(len(SEEN), 3)
|
|
79
|
+
|
|
80
|
+
def test_rate_limit_gives_up_after_max_retries(self):
|
|
81
|
+
LIMIT_LEFT[0] = 10
|
|
82
|
+
with self.assertRaises(ScrapingRabbitError) as caught:
|
|
83
|
+
self.client.youtube_transcript(url="limited")
|
|
84
|
+
self.assertEqual(caught.exception.code, "RATE_LIMITED")
|
|
85
|
+
self.assertEqual(len(SEEN), 3)
|
|
86
|
+
LIMIT_LEFT[0] = 0
|
|
87
|
+
|
|
88
|
+
def test_no_key_is_a_clear_error(self):
|
|
89
|
+
import os
|
|
90
|
+
|
|
91
|
+
os.environ.pop("SCRAPINGRABBIT_API_KEY", None)
|
|
92
|
+
with self.assertRaises(ScrapingRabbitError) as caught:
|
|
93
|
+
ScrapingRabbit(base_url=self.url)
|
|
94
|
+
self.assertEqual(caught.exception.code, "MISSING_API_KEY")
|
|
95
|
+
|
|
96
|
+
def test_network_failure_is_a_scrapingrabbit_error(self):
|
|
97
|
+
client = ScrapingRabbit("sr_live_testkey", base_url="http://127.0.0.1:1/v1", max_retries=0)
|
|
98
|
+
with self.assertRaises(ScrapingRabbitError) as caught:
|
|
99
|
+
client.youtube_transcript(url="abc")
|
|
100
|
+
self.assertEqual(caught.exception.code, "NETWORK_ERROR")
|
|
101
|
+
|
|
102
|
+
def test_async_client_has_the_same_behaviour(self):
|
|
103
|
+
async def run():
|
|
104
|
+
async with AsyncScrapingRabbit("sr_live_testkey", base_url=self.url) as client:
|
|
105
|
+
data = await client.youtube_transcript(url="abc")
|
|
106
|
+
with self.assertRaises(ScrapingRabbitError):
|
|
107
|
+
await client.youtube_transcript(url="missing0000")
|
|
108
|
+
return data
|
|
109
|
+
|
|
110
|
+
self.assertIn("echo", asyncio.run(run()))
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
if __name__ == "__main__":
|
|
114
|
+
unittest.main()
|