scrapeunblocker-haystack 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.
- scrapeunblocker_haystack-0.1.0/.github/workflows/publish.yml +21 -0
- scrapeunblocker_haystack-0.1.0/.github/workflows/test.yml +22 -0
- scrapeunblocker_haystack-0.1.0/.gitignore +7 -0
- scrapeunblocker_haystack-0.1.0/CHANGELOG.md +8 -0
- scrapeunblocker_haystack-0.1.0/LICENSE +202 -0
- scrapeunblocker_haystack-0.1.0/PKG-INFO +157 -0
- scrapeunblocker_haystack-0.1.0/README.md +132 -0
- scrapeunblocker_haystack-0.1.0/pyproject.toml +39 -0
- scrapeunblocker_haystack-0.1.0/src/scrapeunblocker_haystack/__init__.py +4 -0
- scrapeunblocker_haystack-0.1.0/src/scrapeunblocker_haystack/fetcher.py +143 -0
- scrapeunblocker_haystack-0.1.0/src/scrapeunblocker_haystack/search.py +116 -0
- scrapeunblocker_haystack-0.1.0/src/scrapeunblocker_haystack/version.py +1 -0
- scrapeunblocker_haystack-0.1.0/tests/test_components.py +150 -0
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
name: Publish to PyPI
|
|
2
|
+
|
|
3
|
+
on:
|
|
4
|
+
release:
|
|
5
|
+
types: [published]
|
|
6
|
+
|
|
7
|
+
jobs:
|
|
8
|
+
publish:
|
|
9
|
+
runs-on: ubuntu-latest
|
|
10
|
+
environment: pypi
|
|
11
|
+
permissions:
|
|
12
|
+
# Required for PyPI Trusted Publishing (OIDC) - no API token needed.
|
|
13
|
+
id-token: write
|
|
14
|
+
steps:
|
|
15
|
+
- uses: actions/checkout@v4
|
|
16
|
+
- uses: actions/setup-python@v5
|
|
17
|
+
with:
|
|
18
|
+
python-version: "3.12"
|
|
19
|
+
- run: pip install build
|
|
20
|
+
- run: python -m build
|
|
21
|
+
- uses: pypa/gh-action-pypi-publish@release/v1
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
name: Test
|
|
2
|
+
|
|
3
|
+
on:
|
|
4
|
+
push:
|
|
5
|
+
branches: [main]
|
|
6
|
+
pull_request:
|
|
7
|
+
|
|
8
|
+
jobs:
|
|
9
|
+
test:
|
|
10
|
+
runs-on: ubuntu-latest
|
|
11
|
+
strategy:
|
|
12
|
+
matrix:
|
|
13
|
+
python-version: ["3.9", "3.11", "3.13"]
|
|
14
|
+
steps:
|
|
15
|
+
- uses: actions/checkout@v4
|
|
16
|
+
- uses: actions/setup-python@v5
|
|
17
|
+
with:
|
|
18
|
+
python-version: ${{ matrix.python-version }}
|
|
19
|
+
- run: pip install -e . pytest
|
|
20
|
+
- run: pytest tests/ -v
|
|
21
|
+
env:
|
|
22
|
+
SCRAPEUNBLOCKER_API_KEY: dummy-key-for-tests
|
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright [yyyy] [name of copyright owner]
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: scrapeunblocker-haystack
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Haystack integration for ScrapeUnblocker - scrape pages behind anti-bot protections
|
|
5
|
+
Project-URL: Homepage, https://www.scrapeunblocker.com
|
|
6
|
+
Project-URL: Documentation, https://developers.scrapeunblocker.com
|
|
7
|
+
Project-URL: Source, https://github.com/ScrapeUnblocker/scrapeunblocker-haystack
|
|
8
|
+
Project-URL: Issues, https://github.com/ScrapeUnblocker/scrapeunblocker-haystack/issues
|
|
9
|
+
Author-email: ScrapeUnblocker <info@scrapeunblocker.com>
|
|
10
|
+
License-Expression: Apache-2.0
|
|
11
|
+
License-File: LICENSE
|
|
12
|
+
Keywords: anti-bot,haystack,llm,rag,scraping,web-scraping
|
|
13
|
+
Classifier: Development Status :: 4 - Beta
|
|
14
|
+
Classifier: Intended Audience :: Developers
|
|
15
|
+
Classifier: Programming Language :: Python :: 3
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
20
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
21
|
+
Requires-Python: >=3.9
|
|
22
|
+
Requires-Dist: haystack-ai>=2.0.0
|
|
23
|
+
Requires-Dist: requests>=2.31.0
|
|
24
|
+
Description-Content-Type: text/markdown
|
|
25
|
+
|
|
26
|
+
# scrapeunblocker-haystack
|
|
27
|
+
|
|
28
|
+
[Haystack](https://haystack.deepset.ai/) integration for
|
|
29
|
+
[ScrapeUnblocker](https://www.scrapeunblocker.com) - fetch pages that block
|
|
30
|
+
ordinary HTTP requests.
|
|
31
|
+
|
|
32
|
+
ScrapeUnblocker renders web pages in a real browser behind anti-bot protections
|
|
33
|
+
such as Cloudflare, DataDome, PerimeterX and Akamai, so your pipeline gets the
|
|
34
|
+
real content instead of a block page, a captcha, or an empty JavaScript shell.
|
|
35
|
+
|
|
36
|
+
## Installation
|
|
37
|
+
|
|
38
|
+
```bash
|
|
39
|
+
pip install scrapeunblocker-haystack
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
## Setup
|
|
43
|
+
|
|
44
|
+
Get an API key at [scrapeunblocker.com](https://www.scrapeunblocker.com) and
|
|
45
|
+
export it:
|
|
46
|
+
|
|
47
|
+
```bash
|
|
48
|
+
export SCRAPEUNBLOCKER_API_KEY=<your-api-key>
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
Both components read that variable by default, or accept a `Secret` explicitly.
|
|
52
|
+
|
|
53
|
+
## Components
|
|
54
|
+
|
|
55
|
+
### ScrapeUnblockerFetcher
|
|
56
|
+
|
|
57
|
+
Fetches URLs and returns one `Document` per page.
|
|
58
|
+
|
|
59
|
+
```python
|
|
60
|
+
from scrapeunblocker_haystack import ScrapeUnblockerFetcher
|
|
61
|
+
|
|
62
|
+
fetcher = ScrapeUnblockerFetcher()
|
|
63
|
+
result = fetcher.run(urls=["https://example.com"])
|
|
64
|
+
|
|
65
|
+
print(result["documents"][0].content[:200])
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
| Parameter | Default | Description |
|
|
69
|
+
| --- | --- | --- |
|
|
70
|
+
| `api_key` | `SCRAPEUNBLOCKER_API_KEY` env var | ScrapeUnblocker API key |
|
|
71
|
+
| `parsed_data` | `False` | Return AI-parsed structured JSON instead of raw HTML |
|
|
72
|
+
| `proxy_country` | `None` | Two-letter country code for the exit IP |
|
|
73
|
+
| `time_sleep` | `None` | Seconds to wait after load before capturing |
|
|
74
|
+
| `base_url` | `https://api.scrapeunblocker.com` | API base URL |
|
|
75
|
+
| `timeout` | `180` | HTTP timeout in seconds |
|
|
76
|
+
| `raise_on_failure` | `False` | Raise instead of skipping a URL that fails |
|
|
77
|
+
|
|
78
|
+
By default a URL that cannot be fetched is logged and skipped, so one bad URL
|
|
79
|
+
does not discard the rest of the batch.
|
|
80
|
+
|
|
81
|
+
### ScrapeUnblockerWebSearch
|
|
82
|
+
|
|
83
|
+
Searches Google and returns the organic results as `Document` objects, with the
|
|
84
|
+
snippet as content and `title` / `link` / `position` in the metadata.
|
|
85
|
+
|
|
86
|
+
```python
|
|
87
|
+
from scrapeunblocker_haystack import ScrapeUnblockerWebSearch
|
|
88
|
+
|
|
89
|
+
search = ScrapeUnblockerWebSearch(top_k=5)
|
|
90
|
+
result = search.run(query="best web scraping api")
|
|
91
|
+
|
|
92
|
+
for doc in result["documents"]:
|
|
93
|
+
print(doc.meta["title"], doc.meta["link"])
|
|
94
|
+
```
|
|
95
|
+
|
|
96
|
+
| Parameter | Default | Description |
|
|
97
|
+
| --- | --- | --- |
|
|
98
|
+
| `api_key` | `SCRAPEUNBLOCKER_API_KEY` env var | ScrapeUnblocker API key |
|
|
99
|
+
| `pages_to_check` | `1` | How many result pages to scrape |
|
|
100
|
+
| `proxy_country` | `None` | Two-letter country code for localised results |
|
|
101
|
+
| `top_k` | `None` | Keep at most this many results |
|
|
102
|
+
|
|
103
|
+
## In a pipeline
|
|
104
|
+
|
|
105
|
+
Search the web, fetch the pages behind the results, and answer from them:
|
|
106
|
+
|
|
107
|
+
```python
|
|
108
|
+
from haystack import Pipeline
|
|
109
|
+
from haystack.components.builders import ChatPromptBuilder
|
|
110
|
+
from haystack.components.converters import HTMLToDocument
|
|
111
|
+
from haystack.components.generators.chat import OpenAIChatGenerator
|
|
112
|
+
from haystack.dataclasses import ChatMessage
|
|
113
|
+
|
|
114
|
+
from scrapeunblocker_haystack import ScrapeUnblockerFetcher
|
|
115
|
+
|
|
116
|
+
prompt = [
|
|
117
|
+
ChatMessage.from_user(
|
|
118
|
+
"Answer the question using the pages below.\n\n"
|
|
119
|
+
"{% for doc in documents %}{{ doc.content }}\n{% endfor %}\n"
|
|
120
|
+
"Question: {{ question }}"
|
|
121
|
+
)
|
|
122
|
+
]
|
|
123
|
+
|
|
124
|
+
pipe = Pipeline()
|
|
125
|
+
pipe.add_component("fetcher", ScrapeUnblockerFetcher())
|
|
126
|
+
pipe.add_component("converter", HTMLToDocument())
|
|
127
|
+
pipe.add_component("prompt_builder", ChatPromptBuilder(template=prompt, required_variables="*"))
|
|
128
|
+
pipe.add_component("llm", OpenAIChatGenerator())
|
|
129
|
+
|
|
130
|
+
pipe.connect("fetcher.documents", "converter.sources")
|
|
131
|
+
pipe.connect("converter.documents", "prompt_builder.documents")
|
|
132
|
+
pipe.connect("prompt_builder.prompt", "llm.messages")
|
|
133
|
+
|
|
134
|
+
result = pipe.run(
|
|
135
|
+
{
|
|
136
|
+
"fetcher": {"urls": ["https://example.com"]},
|
|
137
|
+
"prompt_builder": {"question": "What is this page about?"},
|
|
138
|
+
}
|
|
139
|
+
)
|
|
140
|
+
print(result["llm"]["replies"][0].text)
|
|
141
|
+
```
|
|
142
|
+
|
|
143
|
+
## Serialization
|
|
144
|
+
|
|
145
|
+
Both components implement `to_dict()` / `from_dict()`, so pipelines using them
|
|
146
|
+
can be saved and reloaded. The API key is serialized as a Haystack `Secret`
|
|
147
|
+
reference, not as its value.
|
|
148
|
+
|
|
149
|
+
## Links
|
|
150
|
+
|
|
151
|
+
- ScrapeUnblocker: https://www.scrapeunblocker.com
|
|
152
|
+
- API documentation: https://developers.scrapeunblocker.com
|
|
153
|
+
- Haystack: https://haystack.deepset.ai
|
|
154
|
+
|
|
155
|
+
## License
|
|
156
|
+
|
|
157
|
+
Apache-2.0
|
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
# scrapeunblocker-haystack
|
|
2
|
+
|
|
3
|
+
[Haystack](https://haystack.deepset.ai/) integration for
|
|
4
|
+
[ScrapeUnblocker](https://www.scrapeunblocker.com) - fetch pages that block
|
|
5
|
+
ordinary HTTP requests.
|
|
6
|
+
|
|
7
|
+
ScrapeUnblocker renders web pages in a real browser behind anti-bot protections
|
|
8
|
+
such as Cloudflare, DataDome, PerimeterX and Akamai, so your pipeline gets the
|
|
9
|
+
real content instead of a block page, a captcha, or an empty JavaScript shell.
|
|
10
|
+
|
|
11
|
+
## Installation
|
|
12
|
+
|
|
13
|
+
```bash
|
|
14
|
+
pip install scrapeunblocker-haystack
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
## Setup
|
|
18
|
+
|
|
19
|
+
Get an API key at [scrapeunblocker.com](https://www.scrapeunblocker.com) and
|
|
20
|
+
export it:
|
|
21
|
+
|
|
22
|
+
```bash
|
|
23
|
+
export SCRAPEUNBLOCKER_API_KEY=<your-api-key>
|
|
24
|
+
```
|
|
25
|
+
|
|
26
|
+
Both components read that variable by default, or accept a `Secret` explicitly.
|
|
27
|
+
|
|
28
|
+
## Components
|
|
29
|
+
|
|
30
|
+
### ScrapeUnblockerFetcher
|
|
31
|
+
|
|
32
|
+
Fetches URLs and returns one `Document` per page.
|
|
33
|
+
|
|
34
|
+
```python
|
|
35
|
+
from scrapeunblocker_haystack import ScrapeUnblockerFetcher
|
|
36
|
+
|
|
37
|
+
fetcher = ScrapeUnblockerFetcher()
|
|
38
|
+
result = fetcher.run(urls=["https://example.com"])
|
|
39
|
+
|
|
40
|
+
print(result["documents"][0].content[:200])
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
| Parameter | Default | Description |
|
|
44
|
+
| --- | --- | --- |
|
|
45
|
+
| `api_key` | `SCRAPEUNBLOCKER_API_KEY` env var | ScrapeUnblocker API key |
|
|
46
|
+
| `parsed_data` | `False` | Return AI-parsed structured JSON instead of raw HTML |
|
|
47
|
+
| `proxy_country` | `None` | Two-letter country code for the exit IP |
|
|
48
|
+
| `time_sleep` | `None` | Seconds to wait after load before capturing |
|
|
49
|
+
| `base_url` | `https://api.scrapeunblocker.com` | API base URL |
|
|
50
|
+
| `timeout` | `180` | HTTP timeout in seconds |
|
|
51
|
+
| `raise_on_failure` | `False` | Raise instead of skipping a URL that fails |
|
|
52
|
+
|
|
53
|
+
By default a URL that cannot be fetched is logged and skipped, so one bad URL
|
|
54
|
+
does not discard the rest of the batch.
|
|
55
|
+
|
|
56
|
+
### ScrapeUnblockerWebSearch
|
|
57
|
+
|
|
58
|
+
Searches Google and returns the organic results as `Document` objects, with the
|
|
59
|
+
snippet as content and `title` / `link` / `position` in the metadata.
|
|
60
|
+
|
|
61
|
+
```python
|
|
62
|
+
from scrapeunblocker_haystack import ScrapeUnblockerWebSearch
|
|
63
|
+
|
|
64
|
+
search = ScrapeUnblockerWebSearch(top_k=5)
|
|
65
|
+
result = search.run(query="best web scraping api")
|
|
66
|
+
|
|
67
|
+
for doc in result["documents"]:
|
|
68
|
+
print(doc.meta["title"], doc.meta["link"])
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
| Parameter | Default | Description |
|
|
72
|
+
| --- | --- | --- |
|
|
73
|
+
| `api_key` | `SCRAPEUNBLOCKER_API_KEY` env var | ScrapeUnblocker API key |
|
|
74
|
+
| `pages_to_check` | `1` | How many result pages to scrape |
|
|
75
|
+
| `proxy_country` | `None` | Two-letter country code for localised results |
|
|
76
|
+
| `top_k` | `None` | Keep at most this many results |
|
|
77
|
+
|
|
78
|
+
## In a pipeline
|
|
79
|
+
|
|
80
|
+
Search the web, fetch the pages behind the results, and answer from them:
|
|
81
|
+
|
|
82
|
+
```python
|
|
83
|
+
from haystack import Pipeline
|
|
84
|
+
from haystack.components.builders import ChatPromptBuilder
|
|
85
|
+
from haystack.components.converters import HTMLToDocument
|
|
86
|
+
from haystack.components.generators.chat import OpenAIChatGenerator
|
|
87
|
+
from haystack.dataclasses import ChatMessage
|
|
88
|
+
|
|
89
|
+
from scrapeunblocker_haystack import ScrapeUnblockerFetcher
|
|
90
|
+
|
|
91
|
+
prompt = [
|
|
92
|
+
ChatMessage.from_user(
|
|
93
|
+
"Answer the question using the pages below.\n\n"
|
|
94
|
+
"{% for doc in documents %}{{ doc.content }}\n{% endfor %}\n"
|
|
95
|
+
"Question: {{ question }}"
|
|
96
|
+
)
|
|
97
|
+
]
|
|
98
|
+
|
|
99
|
+
pipe = Pipeline()
|
|
100
|
+
pipe.add_component("fetcher", ScrapeUnblockerFetcher())
|
|
101
|
+
pipe.add_component("converter", HTMLToDocument())
|
|
102
|
+
pipe.add_component("prompt_builder", ChatPromptBuilder(template=prompt, required_variables="*"))
|
|
103
|
+
pipe.add_component("llm", OpenAIChatGenerator())
|
|
104
|
+
|
|
105
|
+
pipe.connect("fetcher.documents", "converter.sources")
|
|
106
|
+
pipe.connect("converter.documents", "prompt_builder.documents")
|
|
107
|
+
pipe.connect("prompt_builder.prompt", "llm.messages")
|
|
108
|
+
|
|
109
|
+
result = pipe.run(
|
|
110
|
+
{
|
|
111
|
+
"fetcher": {"urls": ["https://example.com"]},
|
|
112
|
+
"prompt_builder": {"question": "What is this page about?"},
|
|
113
|
+
}
|
|
114
|
+
)
|
|
115
|
+
print(result["llm"]["replies"][0].text)
|
|
116
|
+
```
|
|
117
|
+
|
|
118
|
+
## Serialization
|
|
119
|
+
|
|
120
|
+
Both components implement `to_dict()` / `from_dict()`, so pipelines using them
|
|
121
|
+
can be saved and reloaded. The API key is serialized as a Haystack `Secret`
|
|
122
|
+
reference, not as its value.
|
|
123
|
+
|
|
124
|
+
## Links
|
|
125
|
+
|
|
126
|
+
- ScrapeUnblocker: https://www.scrapeunblocker.com
|
|
127
|
+
- API documentation: https://developers.scrapeunblocker.com
|
|
128
|
+
- Haystack: https://haystack.deepset.ai
|
|
129
|
+
|
|
130
|
+
## License
|
|
131
|
+
|
|
132
|
+
Apache-2.0
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["hatchling"]
|
|
3
|
+
build-backend = "hatchling.build"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "scrapeunblocker-haystack"
|
|
7
|
+
dynamic = ["version"]
|
|
8
|
+
description = "Haystack integration for ScrapeUnblocker - scrape pages behind anti-bot protections"
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.9"
|
|
11
|
+
license = "Apache-2.0"
|
|
12
|
+
keywords = ["haystack", "scraping", "web-scraping", "anti-bot", "rag", "llm"]
|
|
13
|
+
authors = [{ name = "ScrapeUnblocker", email = "info@scrapeunblocker.com" }]
|
|
14
|
+
classifiers = [
|
|
15
|
+
"Development Status :: 4 - Beta",
|
|
16
|
+
"Intended Audience :: Developers",
|
|
17
|
+
"Programming Language :: Python :: 3",
|
|
18
|
+
"Programming Language :: Python :: 3.9",
|
|
19
|
+
"Programming Language :: Python :: 3.10",
|
|
20
|
+
"Programming Language :: Python :: 3.11",
|
|
21
|
+
"Programming Language :: Python :: 3.12",
|
|
22
|
+
"Programming Language :: Python :: 3.13",
|
|
23
|
+
]
|
|
24
|
+
dependencies = ["haystack-ai>=2.0.0", "requests>=2.31.0"]
|
|
25
|
+
|
|
26
|
+
[project.urls]
|
|
27
|
+
Homepage = "https://www.scrapeunblocker.com"
|
|
28
|
+
Documentation = "https://developers.scrapeunblocker.com"
|
|
29
|
+
Source = "https://github.com/ScrapeUnblocker/scrapeunblocker-haystack"
|
|
30
|
+
Issues = "https://github.com/ScrapeUnblocker/scrapeunblocker-haystack/issues"
|
|
31
|
+
|
|
32
|
+
[tool.hatch.version]
|
|
33
|
+
path = "src/scrapeunblocker_haystack/version.py"
|
|
34
|
+
|
|
35
|
+
[tool.hatch.build.targets.wheel]
|
|
36
|
+
packages = ["src/scrapeunblocker_haystack"]
|
|
37
|
+
|
|
38
|
+
[tool.pytest.ini_options]
|
|
39
|
+
testpaths = ["tests"]
|
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
"""Haystack component that fetches pages through the ScrapeUnblocker API."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
from typing import Any, Dict, List, Optional
|
|
7
|
+
|
|
8
|
+
import requests
|
|
9
|
+
from haystack import Document, component, default_from_dict, default_to_dict, logging
|
|
10
|
+
from haystack.utils import Secret, deserialize_secrets_inplace
|
|
11
|
+
|
|
12
|
+
logger = logging.getLogger(__name__)
|
|
13
|
+
|
|
14
|
+
DEFAULT_BASE_URL = "https://api.scrapeunblocker.com"
|
|
15
|
+
DEFAULT_TIMEOUT = 180
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
@component
|
|
19
|
+
class ScrapeUnblockerFetcher:
|
|
20
|
+
"""
|
|
21
|
+
Fetches web pages through the ScrapeUnblocker API and returns them as Documents.
|
|
22
|
+
|
|
23
|
+
ScrapeUnblocker renders pages in a real browser behind anti-bot protections
|
|
24
|
+
(Cloudflare, DataDome, PerimeterX, Akamai), so it reaches pages that a plain
|
|
25
|
+
HTTP fetch cannot.
|
|
26
|
+
|
|
27
|
+
### Usage example
|
|
28
|
+
|
|
29
|
+
```python
|
|
30
|
+
from scrapeunblocker_haystack import ScrapeUnblockerFetcher
|
|
31
|
+
|
|
32
|
+
fetcher = ScrapeUnblockerFetcher()
|
|
33
|
+
result = fetcher.run(urls=["https://example.com"])
|
|
34
|
+
print(result["documents"][0].content[:200])
|
|
35
|
+
```
|
|
36
|
+
"""
|
|
37
|
+
|
|
38
|
+
def __init__(
|
|
39
|
+
self,
|
|
40
|
+
api_key: Secret = Secret.from_env_var("SCRAPEUNBLOCKER_API_KEY"),
|
|
41
|
+
parsed_data: bool = False,
|
|
42
|
+
proxy_country: Optional[str] = None,
|
|
43
|
+
time_sleep: Optional[int] = None,
|
|
44
|
+
base_url: str = DEFAULT_BASE_URL,
|
|
45
|
+
timeout: int = DEFAULT_TIMEOUT,
|
|
46
|
+
raise_on_failure: bool = False,
|
|
47
|
+
) -> None:
|
|
48
|
+
"""
|
|
49
|
+
:param api_key: ScrapeUnblocker API key. Read from `SCRAPEUNBLOCKER_API_KEY` by default.
|
|
50
|
+
:param parsed_data: Return AI-parsed structured JSON instead of raw HTML.
|
|
51
|
+
:param proxy_country: Two-letter country code for the exit IP, for geo-restricted content.
|
|
52
|
+
:param time_sleep: Seconds to wait after page load before capturing.
|
|
53
|
+
:param base_url: API base URL. Override to target a different environment.
|
|
54
|
+
:param timeout: HTTP timeout in seconds.
|
|
55
|
+
:param raise_on_failure: Raise instead of skipping when a URL cannot be fetched.
|
|
56
|
+
"""
|
|
57
|
+
self.api_key = api_key
|
|
58
|
+
self.parsed_data = parsed_data
|
|
59
|
+
self.proxy_country = proxy_country
|
|
60
|
+
self.time_sleep = time_sleep
|
|
61
|
+
self.base_url = base_url.rstrip("/")
|
|
62
|
+
self.timeout = timeout
|
|
63
|
+
self.raise_on_failure = raise_on_failure
|
|
64
|
+
|
|
65
|
+
def to_dict(self) -> Dict[str, Any]:
|
|
66
|
+
"""Serialize this component to a dictionary."""
|
|
67
|
+
return default_to_dict(
|
|
68
|
+
self,
|
|
69
|
+
api_key=self.api_key.to_dict(),
|
|
70
|
+
parsed_data=self.parsed_data,
|
|
71
|
+
proxy_country=self.proxy_country,
|
|
72
|
+
time_sleep=self.time_sleep,
|
|
73
|
+
base_url=self.base_url,
|
|
74
|
+
timeout=self.timeout,
|
|
75
|
+
raise_on_failure=self.raise_on_failure,
|
|
76
|
+
)
|
|
77
|
+
|
|
78
|
+
@classmethod
|
|
79
|
+
def from_dict(cls, data: Dict[str, Any]) -> "ScrapeUnblockerFetcher":
|
|
80
|
+
"""Deserialize this component from a dictionary."""
|
|
81
|
+
deserialize_secrets_inplace(data["init_parameters"], keys=["api_key"])
|
|
82
|
+
return default_from_dict(cls, data)
|
|
83
|
+
|
|
84
|
+
def _fetch(self, url: str) -> requests.Response:
|
|
85
|
+
params: Dict[str, Any] = {"url": url}
|
|
86
|
+
if self.parsed_data:
|
|
87
|
+
params["parsed_data"] = True
|
|
88
|
+
if self.proxy_country:
|
|
89
|
+
params["proxy_country"] = self.proxy_country
|
|
90
|
+
if self.time_sleep is not None:
|
|
91
|
+
params["time_sleep"] = self.time_sleep
|
|
92
|
+
|
|
93
|
+
response = requests.post(
|
|
94
|
+
f"{self.base_url}/getPageSource",
|
|
95
|
+
params=params,
|
|
96
|
+
headers={"X-ScrapeUnblocker-Key": self.api_key.resolve_value()},
|
|
97
|
+
timeout=self.timeout,
|
|
98
|
+
)
|
|
99
|
+
response.raise_for_status()
|
|
100
|
+
return response
|
|
101
|
+
|
|
102
|
+
@component.output_types(documents=List[Document])
|
|
103
|
+
def run(self, urls: List[str]) -> Dict[str, List[Document]]:
|
|
104
|
+
"""
|
|
105
|
+
Fetch each URL and return one Document per successfully fetched page.
|
|
106
|
+
|
|
107
|
+
:param urls: URLs to fetch.
|
|
108
|
+
:returns: A dictionary with a `documents` key holding the fetched pages.
|
|
109
|
+
"""
|
|
110
|
+
documents: List[Document] = []
|
|
111
|
+
|
|
112
|
+
for url in urls:
|
|
113
|
+
try:
|
|
114
|
+
response = self._fetch(url)
|
|
115
|
+
except Exception as exc:
|
|
116
|
+
if self.raise_on_failure:
|
|
117
|
+
raise
|
|
118
|
+
# One unreachable URL should not discard the rest of the batch.
|
|
119
|
+
logger.warning(
|
|
120
|
+
"ScrapeUnblocker could not fetch {url}: {error}", url=url, error=str(exc)
|
|
121
|
+
)
|
|
122
|
+
continue
|
|
123
|
+
|
|
124
|
+
if self.parsed_data:
|
|
125
|
+
try:
|
|
126
|
+
content = json.dumps(response.json(), ensure_ascii=False)
|
|
127
|
+
except ValueError:
|
|
128
|
+
content = response.text
|
|
129
|
+
else:
|
|
130
|
+
content = response.text
|
|
131
|
+
|
|
132
|
+
documents.append(
|
|
133
|
+
Document(
|
|
134
|
+
content=content,
|
|
135
|
+
meta={
|
|
136
|
+
"url": url,
|
|
137
|
+
"content_type": response.headers.get("Content-Type", ""),
|
|
138
|
+
"parsed_data": self.parsed_data,
|
|
139
|
+
},
|
|
140
|
+
)
|
|
141
|
+
)
|
|
142
|
+
|
|
143
|
+
return {"documents": documents}
|
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
"""Haystack component that reads Google search results through the ScrapeUnblocker API."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import Any, Dict, List, Optional
|
|
6
|
+
|
|
7
|
+
import requests
|
|
8
|
+
from haystack import Document, component, default_from_dict, default_to_dict
|
|
9
|
+
from haystack.utils import Secret, deserialize_secrets_inplace
|
|
10
|
+
|
|
11
|
+
DEFAULT_BASE_URL = "https://api.scrapeunblocker.com"
|
|
12
|
+
DEFAULT_TIMEOUT = 180
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
@component
|
|
16
|
+
class ScrapeUnblockerWebSearch:
|
|
17
|
+
"""
|
|
18
|
+
Searches Google through the ScrapeUnblocker API and returns the organic results.
|
|
19
|
+
|
|
20
|
+
Each result becomes a Document whose content is the snippet, with the title,
|
|
21
|
+
link and position in the metadata.
|
|
22
|
+
|
|
23
|
+
### Usage example
|
|
24
|
+
|
|
25
|
+
```python
|
|
26
|
+
from scrapeunblocker_haystack import ScrapeUnblockerWebSearch
|
|
27
|
+
|
|
28
|
+
search = ScrapeUnblockerWebSearch()
|
|
29
|
+
result = search.run(query="best web scraping api")
|
|
30
|
+
for doc in result["documents"]:
|
|
31
|
+
print(doc.meta["title"], doc.meta["link"])
|
|
32
|
+
```
|
|
33
|
+
"""
|
|
34
|
+
|
|
35
|
+
def __init__(
|
|
36
|
+
self,
|
|
37
|
+
api_key: Secret = Secret.from_env_var("SCRAPEUNBLOCKER_API_KEY"),
|
|
38
|
+
pages_to_check: int = 1,
|
|
39
|
+
proxy_country: Optional[str] = None,
|
|
40
|
+
top_k: Optional[int] = None,
|
|
41
|
+
base_url: str = DEFAULT_BASE_URL,
|
|
42
|
+
timeout: int = DEFAULT_TIMEOUT,
|
|
43
|
+
) -> None:
|
|
44
|
+
"""
|
|
45
|
+
:param api_key: ScrapeUnblocker API key. Read from `SCRAPEUNBLOCKER_API_KEY` by default.
|
|
46
|
+
:param pages_to_check: How many result pages to scrape.
|
|
47
|
+
:param proxy_country: Two-letter country code for country-specific results.
|
|
48
|
+
:param top_k: Keep at most this many results. `None` keeps all of them.
|
|
49
|
+
:param base_url: API base URL. Override to target a different environment.
|
|
50
|
+
:param timeout: HTTP timeout in seconds.
|
|
51
|
+
"""
|
|
52
|
+
self.api_key = api_key
|
|
53
|
+
self.pages_to_check = pages_to_check
|
|
54
|
+
self.proxy_country = proxy_country
|
|
55
|
+
self.top_k = top_k
|
|
56
|
+
self.base_url = base_url.rstrip("/")
|
|
57
|
+
self.timeout = timeout
|
|
58
|
+
|
|
59
|
+
def to_dict(self) -> Dict[str, Any]:
|
|
60
|
+
"""Serialize this component to a dictionary."""
|
|
61
|
+
return default_to_dict(
|
|
62
|
+
self,
|
|
63
|
+
api_key=self.api_key.to_dict(),
|
|
64
|
+
pages_to_check=self.pages_to_check,
|
|
65
|
+
proxy_country=self.proxy_country,
|
|
66
|
+
top_k=self.top_k,
|
|
67
|
+
base_url=self.base_url,
|
|
68
|
+
timeout=self.timeout,
|
|
69
|
+
)
|
|
70
|
+
|
|
71
|
+
@classmethod
|
|
72
|
+
def from_dict(cls, data: Dict[str, Any]) -> "ScrapeUnblockerWebSearch":
|
|
73
|
+
"""Deserialize this component from a dictionary."""
|
|
74
|
+
deserialize_secrets_inplace(data["init_parameters"], keys=["api_key"])
|
|
75
|
+
return default_from_dict(cls, data)
|
|
76
|
+
|
|
77
|
+
@component.output_types(documents=List[Document])
|
|
78
|
+
def run(self, query: str) -> Dict[str, List[Document]]:
|
|
79
|
+
"""
|
|
80
|
+
Search Google for `query` and return the organic results as Documents.
|
|
81
|
+
|
|
82
|
+
:param query: The search term.
|
|
83
|
+
:returns: A dictionary with a `documents` key holding the organic results.
|
|
84
|
+
"""
|
|
85
|
+
params: Dict[str, Any] = {"keyword": query, "pages_to_check": self.pages_to_check}
|
|
86
|
+
if self.proxy_country:
|
|
87
|
+
params["proxy_country"] = self.proxy_country
|
|
88
|
+
|
|
89
|
+
response = requests.post(
|
|
90
|
+
f"{self.base_url}/serpApi",
|
|
91
|
+
params=params,
|
|
92
|
+
headers={"X-ScrapeUnblocker-Key": self.api_key.resolve_value()},
|
|
93
|
+
timeout=self.timeout,
|
|
94
|
+
)
|
|
95
|
+
response.raise_for_status()
|
|
96
|
+
|
|
97
|
+
payload = response.json()
|
|
98
|
+
organic = payload.get("organic") if isinstance(payload, dict) else None
|
|
99
|
+
results = organic if isinstance(organic, list) else []
|
|
100
|
+
if self.top_k is not None:
|
|
101
|
+
results = results[: self.top_k]
|
|
102
|
+
|
|
103
|
+
documents = [
|
|
104
|
+
Document(
|
|
105
|
+
content=result.get("description") or result.get("title") or "",
|
|
106
|
+
meta={
|
|
107
|
+
"title": result.get("title"),
|
|
108
|
+
"link": result.get("url"),
|
|
109
|
+
"position": result.get("position"),
|
|
110
|
+
"query": query,
|
|
111
|
+
},
|
|
112
|
+
)
|
|
113
|
+
for result in results
|
|
114
|
+
]
|
|
115
|
+
|
|
116
|
+
return {"documents": documents}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
__version__ = "0.1.0"
|
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
"""Unit tests for the ScrapeUnblocker Haystack components."""
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
from unittest.mock import MagicMock, patch
|
|
5
|
+
|
|
6
|
+
import pytest
|
|
7
|
+
from haystack import Document
|
|
8
|
+
from haystack.utils import Secret
|
|
9
|
+
|
|
10
|
+
from scrapeunblocker_haystack import ScrapeUnblockerFetcher, ScrapeUnblockerWebSearch
|
|
11
|
+
|
|
12
|
+
API_KEY = Secret.from_token("test_key")
|
|
13
|
+
# Haystack refuses to serialize token secrets, so to_dict tests use an env-var secret.
|
|
14
|
+
ENV_KEY = Secret.from_env_var("SCRAPEUNBLOCKER_API_KEY")
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def _response(text: str = "<html><title>Test</title></html>", json_data=None) -> MagicMock:
|
|
18
|
+
response = MagicMock()
|
|
19
|
+
response.text = text
|
|
20
|
+
response.headers = {"Content-Type": "text/html"}
|
|
21
|
+
response.raise_for_status.return_value = None
|
|
22
|
+
if json_data is not None:
|
|
23
|
+
response.json.return_value = json_data
|
|
24
|
+
return response
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class TestFetcher:
|
|
28
|
+
def test_defaults(self):
|
|
29
|
+
fetcher = ScrapeUnblockerFetcher(api_key=API_KEY)
|
|
30
|
+
assert fetcher.parsed_data is False
|
|
31
|
+
assert fetcher.base_url == "https://api.scrapeunblocker.com"
|
|
32
|
+
|
|
33
|
+
def test_base_url_trailing_slash_stripped(self):
|
|
34
|
+
fetcher = ScrapeUnblockerFetcher(api_key=API_KEY, base_url="https://example.com/")
|
|
35
|
+
assert fetcher.base_url == "https://example.com"
|
|
36
|
+
|
|
37
|
+
def test_to_dict_and_back(self):
|
|
38
|
+
fetcher = ScrapeUnblockerFetcher(api_key=ENV_KEY, parsed_data=True, proxy_country="de")
|
|
39
|
+
data = fetcher.to_dict()
|
|
40
|
+
assert data["init_parameters"]["parsed_data"] is True
|
|
41
|
+
assert data["init_parameters"]["proxy_country"] == "de"
|
|
42
|
+
|
|
43
|
+
restored = ScrapeUnblockerFetcher.from_dict(data)
|
|
44
|
+
assert restored.parsed_data is True
|
|
45
|
+
assert restored.proxy_country == "de"
|
|
46
|
+
|
|
47
|
+
@patch("scrapeunblocker_haystack.fetcher.requests.post")
|
|
48
|
+
def test_run_single_url(self, mock_post):
|
|
49
|
+
mock_post.return_value = _response()
|
|
50
|
+
fetcher = ScrapeUnblockerFetcher(api_key=API_KEY)
|
|
51
|
+
|
|
52
|
+
result = fetcher.run(urls=["https://example.com"])
|
|
53
|
+
|
|
54
|
+
assert len(result["documents"]) == 1
|
|
55
|
+
doc = result["documents"][0]
|
|
56
|
+
assert isinstance(doc, Document)
|
|
57
|
+
assert "Test" in doc.content
|
|
58
|
+
assert doc.meta["url"] == "https://example.com"
|
|
59
|
+
|
|
60
|
+
_, kwargs = mock_post.call_args
|
|
61
|
+
assert kwargs["headers"]["X-ScrapeUnblocker-Key"] == "test_key"
|
|
62
|
+
assert kwargs["params"] == {"url": "https://example.com"}
|
|
63
|
+
|
|
64
|
+
@patch("scrapeunblocker_haystack.fetcher.requests.post")
|
|
65
|
+
def test_run_forwards_options(self, mock_post):
|
|
66
|
+
mock_post.return_value = _response(json_data={"ok": True})
|
|
67
|
+
fetcher = ScrapeUnblockerFetcher(
|
|
68
|
+
api_key=API_KEY, parsed_data=True, proxy_country="de", time_sleep=5
|
|
69
|
+
)
|
|
70
|
+
fetcher.run(urls=["https://example.com"])
|
|
71
|
+
|
|
72
|
+
_, kwargs = mock_post.call_args
|
|
73
|
+
assert kwargs["params"]["parsed_data"] is True
|
|
74
|
+
assert kwargs["params"]["proxy_country"] == "de"
|
|
75
|
+
assert kwargs["params"]["time_sleep"] == 5
|
|
76
|
+
|
|
77
|
+
@patch("scrapeunblocker_haystack.fetcher.requests.post")
|
|
78
|
+
def test_parsed_data_serialised_as_json(self, mock_post):
|
|
79
|
+
mock_post.return_value = _response(json_data={"title": "Test", "price": "9.99"})
|
|
80
|
+
fetcher = ScrapeUnblockerFetcher(api_key=API_KEY, parsed_data=True)
|
|
81
|
+
|
|
82
|
+
result = fetcher.run(urls=["https://example.com"])
|
|
83
|
+
|
|
84
|
+
assert json.loads(result["documents"][0].content) == {"title": "Test", "price": "9.99"}
|
|
85
|
+
|
|
86
|
+
@patch("scrapeunblocker_haystack.fetcher.requests.post")
|
|
87
|
+
def test_failure_is_skipped_by_default(self, mock_post):
|
|
88
|
+
mock_post.side_effect = [Exception("boom"), _response()]
|
|
89
|
+
fetcher = ScrapeUnblockerFetcher(api_key=API_KEY)
|
|
90
|
+
|
|
91
|
+
result = fetcher.run(urls=["https://broken.com", "https://ok.com"])
|
|
92
|
+
|
|
93
|
+
assert len(result["documents"]) == 1
|
|
94
|
+
assert result["documents"][0].meta["url"] == "https://ok.com"
|
|
95
|
+
|
|
96
|
+
@patch("scrapeunblocker_haystack.fetcher.requests.post")
|
|
97
|
+
def test_failure_raises_when_requested(self, mock_post):
|
|
98
|
+
mock_post.side_effect = Exception("boom")
|
|
99
|
+
fetcher = ScrapeUnblockerFetcher(api_key=API_KEY, raise_on_failure=True)
|
|
100
|
+
|
|
101
|
+
with pytest.raises(Exception, match="boom"):
|
|
102
|
+
fetcher.run(urls=["https://broken.com"])
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
class TestWebSearch:
|
|
106
|
+
@patch("scrapeunblocker_haystack.search.requests.post")
|
|
107
|
+
def test_run(self, mock_post):
|
|
108
|
+
mock_post.return_value = _response(
|
|
109
|
+
json_data={
|
|
110
|
+
"organic": [
|
|
111
|
+
{"title": "First", "url": "https://a.com", "description": "snippet a", "position": "1"},
|
|
112
|
+
{"title": "Second", "url": "https://b.com", "description": "snippet b", "position": "2"},
|
|
113
|
+
]
|
|
114
|
+
}
|
|
115
|
+
)
|
|
116
|
+
search = ScrapeUnblockerWebSearch(api_key=API_KEY)
|
|
117
|
+
|
|
118
|
+
result = search.run(query="test query")
|
|
119
|
+
|
|
120
|
+
assert len(result["documents"]) == 2
|
|
121
|
+
assert result["documents"][0].content == "snippet a"
|
|
122
|
+
assert result["documents"][0].meta["title"] == "First"
|
|
123
|
+
assert result["documents"][0].meta["link"] == "https://a.com"
|
|
124
|
+
assert result["documents"][0].meta["query"] == "test query"
|
|
125
|
+
|
|
126
|
+
_, kwargs = mock_post.call_args
|
|
127
|
+
assert kwargs["params"]["keyword"] == "test query"
|
|
128
|
+
|
|
129
|
+
@patch("scrapeunblocker_haystack.search.requests.post")
|
|
130
|
+
def test_top_k(self, mock_post):
|
|
131
|
+
mock_post.return_value = _response(
|
|
132
|
+
json_data={"organic": [{"title": str(i), "url": "", "description": str(i)} for i in range(10)]}
|
|
133
|
+
)
|
|
134
|
+
search = ScrapeUnblockerWebSearch(api_key=API_KEY, top_k=3)
|
|
135
|
+
|
|
136
|
+
assert len(search.run(query="q")["documents"]) == 3
|
|
137
|
+
|
|
138
|
+
@patch("scrapeunblocker_haystack.search.requests.post")
|
|
139
|
+
def test_missing_organic_returns_empty(self, mock_post):
|
|
140
|
+
mock_post.return_value = _response(json_data={"totalResults": None})
|
|
141
|
+
search = ScrapeUnblockerWebSearch(api_key=API_KEY)
|
|
142
|
+
|
|
143
|
+
assert search.run(query="q")["documents"] == []
|
|
144
|
+
|
|
145
|
+
def test_to_dict_and_back(self):
|
|
146
|
+
search = ScrapeUnblockerWebSearch(api_key=ENV_KEY, top_k=5, proxy_country="us")
|
|
147
|
+
data = search.to_dict()
|
|
148
|
+
restored = ScrapeUnblockerWebSearch.from_dict(data)
|
|
149
|
+
assert restored.top_k == 5
|
|
150
|
+
assert restored.proxy_country == "us"
|