├── .github
└── workflows
│ ├── patchright_tests.yml
│ └── patchright_workflow.yml
├── .gitignore
├── LICENSE
├── README.md
├── patch_python_package.py
├── pyproject.toml
└── utils
├── modify_tests.py
└── release_version_check.sh
/.github/workflows/patchright_tests.yml:
--------------------------------------------------------------------------------
1 | name: Patchright Chromium Tests
2 |
3 | on:
4 | push:
5 | branches: [main]
6 | pull_request:
7 | branches: [main]
8 |
9 | jobs:
10 | run-playwright-tests:
11 | runs-on: ubuntu-latest
12 |
13 | steps:
14 | - name: Checkout Repository
15 | uses: actions/checkout@v3
16 |
17 | - name: Set up Python
18 | uses: actions/setup-python@v4
19 | with:
20 | python-version: '3.11'
21 |
22 | - name: Install Dependencies
23 | run: |
24 | python -m pip install --upgrade pip
25 | pip install pytest
26 |
27 | - name: Install Playwright-Python Package
28 | run: |
29 | git clone https://github.com/microsoft/playwright-python --branch $(curl --silent "https://api.github.com/repos/Kaliiiiiiiiii-Vinyzu/patchright/releases/latest" | grep '"tag_name"' | sed -E 's/.*"([^"]+)".*/\1/')
30 | cd playwright-python
31 | python -m pip install --upgrade pip
32 | pip install -r local-requirements.txt
33 | pip install -e .
34 | pip install black toml
35 |
36 | - name: Patch Playwright-Python Package
37 | run: |
38 | python patch_python_package.py
39 | python -m black playwright-python
40 |
41 | - name: Build Patchright-Python Package
42 | run: |
43 | cd playwright-python
44 | pip install -e .
45 | for wheel in $(python setup.py --list-wheels); do
46 | PLAYWRIGHT_TARGET_WHEEL=$wheel python -m build --wheel
47 | done
48 |
49 | - name: Install Local Patchright Package
50 | run: |
51 | cd playwright-python
52 | pip install dist/patchright-*-manylinux1_x86_64.whl
53 |
54 | - name: Install Playwright Browsers
55 | run: |
56 | python -m patchright install --with-deps chromium
57 |
58 | - name: Clone Playwright-Python Tests
59 | run: |
60 | cp -r playwright-python/tests ./tests
61 |
62 | - name: Modify Tests
63 | run: |
64 | python utils/modify_tests.py
65 |
66 | - name: Run Chromium Tests
67 | run: |
68 | xvfb-run pytest --browser=chromium --disable-warnings --timeout 90 tests/sync/
69 | xvfb-run pytest --browser=chromium --disable-warnings --timeout 90 tests/async/
--------------------------------------------------------------------------------
/.github/workflows/patchright_workflow.yml:
--------------------------------------------------------------------------------
1 | name: PatchRight-Python Workflow
2 |
3 | on:
4 | # enabling manual trigger
5 | workflow_dispatch:
6 | inputs:
7 | version:
8 | description: 'Playwright Version'
9 | default: ''
10 | # running every hour
11 | schedule:
12 | - cron: '48 * * * *'
13 |
14 |
15 | permissions:
16 | actions: none
17 | attestations: none
18 | checks: none
19 | contents: write
20 | deployments: none
21 | id-token: write # For trusted Publishing
22 | issues: none
23 | discussions: none
24 | packages: none
25 | pages: none
26 | pull-requests: none
27 | repository-projects: none
28 | security-events: none
29 | statuses: none
30 |
31 |
32 | env:
33 | REPO: ${{ github.repository }}
34 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
35 |
36 | jobs:
37 | patchright-workflow:
38 | name: "Patchright-Python Workflow: Install, Patch, Build and Publish Patchright Python Package"
39 | runs-on: ubuntu-24.04
40 | environment:
41 | name: pypi
42 | url: https://pypi.org/p/patchright
43 | steps:
44 | - uses: actions/checkout@v4
45 | - name: Set up Python 3.11
46 | uses: actions/setup-python@v5
47 | with:
48 | python-version: '3.11'
49 |
50 | - name: Check Release Version
51 | id: version_check
52 | run: |
53 | if [ -n "${{ github.event.inputs.version }}" ]; then
54 | echo "proceed=true" >>$GITHUB_OUTPUT
55 | echo "playwright_version=${{ github.event.inputs.version }}" >> $GITHUB_ENV
56 | else
57 | chmod +x utils/release_version_check.sh
58 | utils/release_version_check.sh
59 | fi
60 |
61 | - name: Install Playwright-Python Package
62 | if: steps.version_check.outputs.proceed == 'true'
63 | run: |
64 | git clone https://github.com/microsoft/playwright-python --branch ${{ env.playwright_version }}
65 | cd playwright-python
66 | python -m pip install --upgrade pip
67 | pip install -r local-requirements.txt
68 | pip install -e .
69 | pip install black toml
70 |
71 | - name: Patch Playwright-Python Package
72 | if: steps.version_check.outputs.proceed == 'true'
73 | run: |
74 | python patch_python_package.py
75 | python -m black playwright-python
76 |
77 | - name: Build Patchright-Python Package
78 | if: steps.version_check.outputs.proceed == 'true'
79 | run: |
80 | cd playwright-python
81 | pip install -e .
82 | for wheel in $(python setup.py --list-wheels); do
83 | PLAYWRIGHT_TARGET_WHEEL=$wheel python -m build --wheel
84 | done
85 |
86 | - name: Create Empty Versioning Release
87 | if: steps.version_check.outputs.proceed == 'true'
88 | uses: actions/create-release@v1
89 | with:
90 | tag_name: ${{ env.playwright_version }}
91 | release_name: ${{ env.playwright_version }}
92 | body: |
93 | This is an automatic deployment in response to a new release of [microsoft/playwright-python](https://github.com/microsoft/playwright-python).
94 | This Release is only used for Versioning.
95 | draft: false
96 | prerelease: false
97 |
98 | - name: Publish Patchright-Python Package
99 | if: steps.version_check.outputs.proceed == 'true'
100 | uses: pypa/gh-action-pypi-publish@release/v1
101 | with:
102 | packages-dir: playwright-python/dist/
103 | verbose: true
104 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # Byte-compiled / optimized / DLL files
2 | __pycache__/
3 | *.py[cod]
4 | *$py.class
5 |
6 | # C extensions
7 | *.so
8 |
9 | # Distribution / packaging
10 | .Python
11 | build/
12 | develop-eggs/
13 | dist/
14 | downloads/
15 | eggs/
16 | .eggs/
17 | lib/
18 | lib64/
19 | parts/
20 | sdist/
21 | var/
22 | wheels/
23 | share/python-wheels/
24 | *.egg-info/
25 | .installed.cfg
26 | *.egg
27 | MANIFEST
28 |
29 | # PyInstaller
30 | # Usually these files are written by a python script from a template
31 | # before PyInstaller builds the exe, so as to inject date/other infos into it.
32 | *.manifest
33 | *.spec
34 |
35 | # Installer logs
36 | pip-log.txt
37 | pip-delete-this-directory.txt
38 |
39 | # Unit test / coverage reports
40 | htmlcov/
41 | .tox/
42 | .nox/
43 | .coverage
44 | .coverage.*
45 | .cache
46 | nosetests.xml
47 | coverage.xml
48 | *.cover
49 | *.py,cover
50 | .hypothesis/
51 | .pytest_cache/
52 | cover/
53 |
54 | # Translations
55 | *.mo
56 | *.pot
57 |
58 | # Django stuff:
59 | *.log
60 | local_settings.py
61 | db.sqlite3
62 | db.sqlite3-journal
63 |
64 | # Flask stuff:
65 | instance/
66 | .webassets-cache
67 |
68 | # Scrapy stuff:
69 | .scrapy
70 |
71 | # Sphinx documentation
72 | docs/_build/
73 |
74 | # PyBuilder
75 | .pybuilder/
76 | target/
77 |
78 | # Jupyter Notebook
79 | .ipynb_checkpoints
80 |
81 | # IPython
82 | profile_default/
83 | ipython_config.py
84 |
85 | # pyenv
86 | # For a library or package, you might want to ignore these files since the code is
87 | # intended to run in multiple environments; otherwise, check them in:
88 | # .python-version
89 |
90 | # pipenv
91 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
92 | # However, in case of collaboration, if having platform-specific dependencies or dependencies
93 | # having no cross-platform support, pipenv may install dependencies that don't work, or not
94 | # install all needed dependencies.
95 | #Pipfile.lock
96 |
97 | # poetry
98 | # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
99 | # This is especially recommended for binary packages to ensure reproducibility, and is more
100 | # commonly ignored for libraries.
101 | # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
102 | #poetry.lock
103 |
104 | # pdm
105 | # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
106 | #pdm.lock
107 | # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
108 | # in version control.
109 | # https://pdm.fming.dev/latest/usage/project/#working-with-version-control
110 | .pdm.toml
111 | .pdm-python
112 | .pdm-build/
113 |
114 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
115 | __pypackages__/
116 |
117 | # Celery stuff
118 | celerybeat-schedule
119 | celerybeat.pid
120 |
121 | # SageMath parsed files
122 | *.sage.py
123 |
124 | # Environments
125 | .env
126 | .venv
127 | env/
128 | venv/
129 | ENV/
130 | env.bak/
131 | venv.bak/
132 |
133 | # Spyder project settings
134 | .spyderproject
135 | .spyproject
136 |
137 | # Rope project settings
138 | .ropeproject
139 |
140 | # mkdocs documentation
141 | /site
142 |
143 | # mypy
144 | .mypy_cache/
145 | .dmypy.json
146 | dmypy.json
147 |
148 | # Pyre type checker
149 | .pyre/
150 |
151 | # pytype static type analyzer
152 | .pytype/
153 |
154 | # Cython debug symbols
155 | cython_debug/
156 |
157 | # PyCharm
158 | # JetBrains specific template is maintained in a separate JetBrains.gitignore that can
159 | # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
160 | # and can be added to the global gitignore or merged into this file. For a more nuclear
161 | # option (not recommended) you can uncomment the following to ignore the entire idea folder.
162 | .idea/
163 | .DS_Store
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "[]"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright 2024 Vinyzu
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
202 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 |
2 | 🎭 Patchright Python
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 | #### Patchright is a patched and undetected version of the Playwright Testing and Automation Framework. It can be used as a drop-in replacement for Playwright.
32 |
33 | > [!NOTE]
34 | > This repository serves the Patchright-Python Package. To use Patchright with NodeJS, check out the [NodeJS Package](https://github.com/Kaliiiiiiiiii-Vinyzu/patchright-nodejs).
35 | > Also check out the main [Patchright Driver Repository](https://github.com/Kaliiiiiiiiii-Vinyzu/patchright)
36 |
37 | ---
38 |
39 | ## Install it from PyPI
40 |
41 | ```bash
42 | # Install Patchright with Pip from PyPI
43 | pip install patchright
44 | ```
45 |
46 | ```bash
47 | # Install Chromium-Driver for Patchright
48 | patchright install chromium
49 | ```
50 |
51 | ---
52 |
53 | ## Usage
54 | #### Just change the import and use it like playwright. Patchright is a drop-in-replacement for Playwright!
55 |
56 | > [!IMPORTANT]
57 | > Patchright only patches CHROMIUM based browsers. Firefox and Webkit are not supported.
58 |
59 | ```py
60 | # patchright here!
61 | from patchright.sync_api import sync_playwright
62 |
63 | with sync_playwright() as p:
64 | browser = p.chromium.launch()
65 | page = browser.new_page()
66 | page.goto('http://playwright.dev')
67 | page.screenshot(path=f'example-{p.chromium.name}.png')
68 | browser.close()
69 | ```
70 |
71 | ```py
72 | import asyncio
73 | # patchright here!
74 | from patchright.async_api import async_playwright
75 |
76 | async def main():
77 | async with async_playwright() as p:
78 | browser = await p.chromium.launch()
79 | page = await browser.new_page()
80 | await page.goto('http://playwright.dev')
81 | await page.screenshot(path=f'example-{p.chromium.name}.png')
82 | await browser.close()
83 |
84 | asyncio.run(main())
85 | ```
86 |
87 | ### Best Practice - use Chrome without Fingerprint Injection
88 |
89 | To be completely undetected, use the following configuration:
90 | ```py
91 | playwright.chromium.launch_persistent_context(
92 | user_data_dir="...",
93 | channel="chrome",
94 | headless=False,
95 | no_viewport=True,
96 | # do NOT add custom browser headers or user_agent
97 | ...
98 | )
99 | ```
100 |
101 | > [!NOTE]
102 | > We recommend using Google Chrome instead of Chromium.
103 | > You can install it via `patchright install chrome` (or via any other installation method) and use it with `channel="chrome"`.
104 |
105 | ---
106 |
107 | ## Patches
108 |
109 | ### [Runtime.enable](https://vanilla.aslushnikov.com/?Runtime.enable) Leak
110 | This is the biggest Patch Patchright uses. To avoid detection by this leak, patchright avoids using [Runtime.enable](https://vanilla.aslushnikov.com/?Runtime.enable) by executing Javascript in (isolated) ExecutionContexts.
111 |
112 | ### [Console.enable](https://vanilla.aslushnikov.com/?Console.enable) Leak
113 | Patchright patches this leak by disabling the Console API all together. This means, console functionality will not work in Patchright. If you really need the console, you might be better off using Javascript loggers, although they also can be easily detected.
114 |
115 | ### Command Flags Leaks
116 | Patchright tweaks the Playwright Default Args to avoid detection by Command Flag Leaks. This (most importantly) affects:
117 | - `--disable-blink-features=AutomationControlled` (added) to avoid navigator.webdriver detection.
118 | - `--enable-automation` (removed) to avoid navigator.webdriver detection.
119 | - `--disable-popup-blocking` (removed) to avoid popup crashing.
120 | - `--disable-component-update` (removed) to avoid detection as a Stealth Driver.
121 | - `--disable-default-apps` (removed) to enable default apps.
122 | - `--disable-extensions` (removed) to enable extensions
123 |
124 | ### General Leaks
125 | Patchright patches some general leaks in the Playwright codebase. This mainly includes poor setups and obvious detection points.
126 |
127 | ### Closed Shadow Roots
128 | Patchright is able to interact with elements in Closed Shadow Roots. Just use normal locators and Patchright will do the rest.
129 |
130 | Patchright is now also able to use XPaths in Closed Shadow Roots.
131 |
132 | ---
133 |
134 | ## Stealth
135 |
136 | With the right setup, Patchright currently is considered undetectable.
137 | Patchright passes:
138 | - [Brotector](https://kaliiiiiiiiii.github.io/brotector/) ✅ (with [CDP-Patches](https://github.com/Kaliiiiiiiiii-Vinyzu/CDP-Patches/))
139 | - [Cloudflare](https://cloudflare.com/) ✅
140 | - [Kasada](https://www.kasada.io/) ✅
141 | - [Akamai](https://www.akamai.com/products/bot-manager/) ✅
142 | - [Shape/F5](https://www.f5.com/) ✅
143 | - [Bet365](https://bet365.com/) ✅
144 | - [Datadome](https://datadome.co/products/bot-protection/) ✅
145 | - [Fingerprint.com](https://fingerprint.com/products/bot-detection/) ✅
146 | - [CreepJS](https://abrahamjuliot.github.io/creepjs/) ✅
147 | - [Sannysoft](https://bot.sannysoft.com/) ✅
148 | - [Incolumitas](https://bot.incolumitas.com/) ✅
149 | - [IPHey](https://iphey.com/) ✅
150 | - [Browserscan](https://browserscan.net/) ✅
151 | - [Pixelscan](https://pixelscan.net/) ✅
152 |
153 | ---
154 |
155 | ## Documentation and API Reference
156 | See the original [Playwright Documentation](https://playwright.dev/python/docs/intro) and [API Reference](https://playwright.dev/python/docs/api/class-playwright)
157 |
158 | ## Extended Patchright API
159 | #### **`evaluate`** Method ([`Frame.evaluate`](https://playwright.dev/python/docs/api/class-frame#frame-evaluate), [`Page.evaluate`](https://playwright.dev/python/docs/api/class-page#page-evaluate), [`Locator.evaluate`](https://playwright.dev/python/docs/api/class-locator#locator-evaluate), [`Worker.evaluate`](https://playwright.dev/python/docs/api/class-worker#worker-evaluate), [`JSHandle.evaluate`](https://playwright.dev/python/docs/api/class-jshandle#js-handle-evaluate))
160 | - Added `isolated_context` to choose Execution Context (Main/Isolated). `Bool` (*optional*, Defaults to `True`)
161 | ```diff
162 | object.evaluate(
163 | expression: str,
164 | arg: typing.Optional[typing.Any] = None,
165 | ...,
166 | + isolated_context: typing.Optional[bool] = True
167 | )
168 | ```
169 |
170 | #### **`evaluate_handle`** Method ([`Frame.evaluate_handle`](https://playwright.dev/python/docs/api/class-frame#frame-evaluate-handle), [`Page.evaluate_handle`](https://playwright.dev/python/docs/api/class-page#page-evaluate-handle), [`Locator.evaluate_handle`](https://playwright.dev/python/docs/api/class-locator#locator-evaluate-handle), [`Worker.evaluate_handle`](https://playwright.dev/python/docs/api/class-worker#worker-evaluate-handle), [`JSHandle.evaluate`](https://playwright.dev/python/docs/api/class-jshandle#js-handle-evaluate-handle))
171 | - Added `isolated_context` to choose Execution Context (Main/Isolated). `Bool` (*optional*, Defaults to `True`)
172 | ```diff
173 | object.evaluate_handle(
174 | expression: str,
175 | arg: typing.Optional[typing.Any] = None,
176 | ...,
177 | + isolated_context: typing.Optional[bool] = True
178 | )
179 | ```
180 |
181 | #### **`evaluate_all`** Method ([`Locator.evaluate_all`](https://playwright.dev/python/docs/next/api/class-locator#locator-evaluate-all))
182 | - Added `isolated_context` to choose Execution Context (Main/Isolated). `Bool` (*optional*, Defaults to `True`)
183 | ```diff
184 | Locator.evaluate_all(
185 | expression: str,
186 | arg: typing.Optional[typing.Any] = None,
187 | ...,
188 | + isolated_context: typing.Optional[bool] = True
189 | )
190 | ```
191 |
192 |
193 | ---
194 |
195 | ## Bugs
196 | #### The bugs are documented in the [Patchright Driver Repository](https://github.com/Kaliiiiiiiiii-Vinyzu/patchright#bugs).
197 |
198 | ---
199 |
200 | ### TODO
201 | #### The TODO is documented in the [Patchright Driver Repository](https://github.com/Kaliiiiiiiiii-Vinyzu/patchright#todo).
202 |
203 |
204 | ---
205 |
206 | ## Development
207 |
208 | Deployment of new Patchright versions are automatic, but bugs due to Playwright codebase changes may occur. Fixes for these bugs might take a few days to be released.
209 |
210 | ---
211 |
212 | ## Support our work
213 |
214 | If you choose to support our work, please contact [@vinyzu](https://discord.com/users/935224495126487150) or [@steve_abcdef](https://discord.com/users/936292409426477066) on Discord.
215 |
216 | ---
217 |
218 | ## Copyright and License
219 | © [Vinyzu](https://github.com/Vinyzu/)
220 |
221 | Patchright is licensed [Apache 2.0](https://choosealicense.com/licenses/apache-2.0/)
222 |
223 | ---
224 |
225 | ## Disclaimer
226 |
227 | This repository is provided for **educational purposes only**. \
228 | No warranties are provided regarding accuracy, completeness, or suitability for any purpose. **Use at your own risk**—the authors and maintainers assume **no liability** for **any damages**, **legal issues**, or **warranty breaches** resulting from use, modification, or distribution of this code.\
229 | **Any misuse or legal violations are the sole responsibility of the user**.
230 |
231 | ---
232 |
233 | ## Authors
234 |
235 | #### Active Maintainer: [Vinyzu](https://github.com/Vinyzu/) Co-Maintainer: [Kaliiiiiiiiii](https://github.com/kaliiiiiiiiii/)
--------------------------------------------------------------------------------
/patch_python_package.py:
--------------------------------------------------------------------------------
1 | import ast
2 | import glob
3 | import os
4 |
5 | import toml
6 |
7 | patchright_version = os.environ.get('playwright_version')
8 | patchright_version = "1.52.5"
9 |
10 | def patch_file(file_path: str, patched_tree: ast.AST) -> None:
11 | with open(file_path, "w") as f:
12 | f.write(ast.unparse(ast.fix_missing_locations(patched_tree)))
13 |
14 | # Adding _repo_version.py (Might not be intended but fixes the build)
15 | with open("playwright-python/playwright/_repo_version.py", "w") as f:
16 | f.write(f"version = '{patchright_version}'")
17 |
18 | # Patching pyproject.toml
19 | with open("playwright-python/pyproject.toml", "r") as f:
20 | pyproject_source = toml.load(f)
21 |
22 | pyproject_source["project"]["name"] = "patchright"
23 | pyproject_source["project"]["description"] = "Undetected Python version of the Playwright testing and automation library."
24 | pyproject_source["project"]["authors"] = [{'name': 'Microsoft Corporation, patched by github.com/Kaliiiiiiiiii-Vinyzu/'}]
25 |
26 | pyproject_source["project"]["urls"]["homepage"] = "https://github.com/Kaliiiiiiiiii-Vinyzu/patchright-python"
27 | pyproject_source["project"]["urls"]["Release notes"] = "https://github.com/Kaliiiiiiiiii-Vinyzu/patchright-python/releases"
28 | pyproject_source["project"]["urls"]["Bug Reports"] = "https://github.com/Kaliiiiiiiiii-Vinyzu/patchright-python/issues"
29 | pyproject_source["project"]["urls"]["homeSource Codepage"] = "https://github.com/Kaliiiiiiiiii-Vinyzu/patchright-python"
30 |
31 | del pyproject_source["project"]["scripts"]["playwright"]
32 | pyproject_source["project"]["scripts"]["patchright"] = "patchright.__main__:main"
33 | pyproject_source["project"]["entry-points"]["pyinstaller40"]["hook-dirs"] = "patchright._impl.__pyinstaller:get_hook_dirs"
34 |
35 | pyproject_source["tool"]["setuptools"]["packages"] = ['patchright', 'patchright.async_api', 'patchright.sync_api', 'patchright._impl', 'patchright._impl.__pyinstaller']
36 | pyproject_source["tool"]["setuptools_scm"] = {'version_file': 'patchright/_repo_version.py'}
37 |
38 | with open("playwright-python/pyproject.toml", "w") as f:
39 | toml.dump(pyproject_source, f)
40 |
41 | # Patching setup.py
42 | with open("playwright-python/setup.py") as f:
43 | setup_source = f.read()
44 | setup_tree = ast.parse(setup_source)
45 |
46 | for node in ast.walk(setup_tree):
47 | # Modify driver_version
48 | if isinstance(node, ast.Assign) and isinstance(node.value, ast.Constant) and isinstance(node.targets[0], ast.Name):
49 | if node.targets[0].id == "driver_version" and node.value.value.startswith("1."):
50 | node.value.value = node.value.value.split("-")[0]
51 |
52 | # Modify url
53 | if isinstance(node, ast.Assign) and isinstance(node.value, ast.Constant) and isinstance(node.targets[0], ast.Name):
54 | if node.targets[0].id == "url" and node.value.value == "https://playwright.azureedge.net/builds/driver/":
55 | node.value = ast.JoinedStr(
56 | values=[
57 | ast.Constant(value='https://github.com/Kaliiiiiiiiii-Vinyzu/patchright/releases/download/v'),
58 | ast.FormattedValue(value=ast.Name(id='driver_version', ctx=ast.Load()), conversion=-1),
59 | ast.Constant(value='/')
60 | ]
61 | )
62 |
63 | # Modify Curl Call
64 | if isinstance(node, ast.Call) and isinstance(node.func, ast.Attribute) and isinstance(node.func.value, ast.Name) and len(node.args) >= 1 and isinstance(node.args[0], ast.List) and len(node.args[0].elts) == 4:
65 | if node.func.value.id == "subprocess" and node.func.attr == "check_call" and node.args[0].elts[0].value == "curl":
66 | node.args[0].elts.insert(1, ast.Constant(value="-L"))
67 |
68 | # Modify Shutil Call
69 | if isinstance(node, ast.Call) and isinstance(node.func, ast.Attribute) and isinstance(node.func.value, ast.Name) and len(node.args) >= 1 and isinstance(node.args[0], ast.Constant):
70 | if node.func.value.id == "shutil" and node.func.attr == "rmtree" and node.args[0].value == "playwright.egg-info":
71 | node.args[0].value = "patchright.egg-info"
72 |
73 | # Modify Os Makedirs Call
74 | if isinstance(node, ast.Call) and isinstance(node.func, ast.Attribute) and isinstance(node.func.value, ast.Name) and len(node.args) >= 1 and isinstance(node.args[0], ast.Constant):
75 | if node.func.value.id == "os" and node.func.attr == "makedirs" and node.args[0].value == "playwright/driver":
76 | node.args[0].value = "patchright/driver"
77 |
78 | # Modify Zip Write Call
79 | if isinstance(node, ast.Call) and isinstance(node.func, ast.Attribute) and isinstance(node.func.value, ast.Name) and len(node.args) >= 2 and isinstance(node.args[1], ast.JoinedStr):
80 | if node.func.value.id == "zip" and node.func.attr == "write" and node.args[1].values[0].value == "playwright/driver/":
81 | node.args[1].values[0].value = "patchright/driver/"
82 |
83 | # Modify Zip Writestr Call
84 | if isinstance(node, ast.Call) and isinstance(node.func, ast.Attribute) and isinstance(node.func.value, ast.Name) and len(node.args) >= 1 and isinstance(node.args[0], ast.Constant):
85 | if node.func.value.id == "zip" and node.func.attr == "writestr" and node.args[0].value == "playwright/driver/README.md":
86 | node.args[0].value = "patchright/driver/README.md"
87 |
88 | # Modify Extractall Call
89 | if isinstance(node, ast.Call) and isinstance(node.func, ast.Name) and len(node.args) >= 2 and isinstance(node.args[1], ast.Constant):
90 | if node.func.id == "extractall" and node.args[1].value == "playwright/driver":
91 | node.args[1].value = "patchright/driver"
92 |
93 | # Modify Setup Call
94 | if isinstance(node, ast.Call) and isinstance(node.func, ast.Name):
95 | if node.func.id == "setup":
96 | node.keywords.append(ast.keyword(
97 | arg="version",
98 | value=ast.Constant(value=patchright_version)
99 | ))
100 |
101 | patch_file("playwright-python/setup.py", setup_tree)
102 |
103 | # Patching playwright/_impl/__pyinstaller/hook-playwright.async_api.py
104 | with open("playwright-python/playwright/_impl/__pyinstaller/hook-playwright.async_api.py") as f:
105 | async_api_source = f.read()
106 | async_api_tree = ast.parse(async_api_source)
107 |
108 | for node in ast.walk(async_api_tree):
109 | if isinstance(node, ast.Call) and isinstance(node.func, ast.Name) and len(node.args) == 1 and isinstance(node.args[0], ast.Constant):
110 | if node.func.id == "collect_data_files" and node.args[0].value == "playwright":
111 | node.args[0].value = "patchright"
112 |
113 | patch_file("playwright-python/playwright/_impl/__pyinstaller/hook-playwright.async_api.py", async_api_tree)
114 |
115 | # Patching playwright/_impl/__pyinstaller/hook-playwright.sync_api.py
116 | with open("playwright-python/playwright/_impl/__pyinstaller/hook-playwright.sync_api.py") as f:
117 | async_api_source = f.read()
118 | async_api_tree = ast.parse(async_api_source)
119 |
120 | for node in ast.walk(async_api_tree):
121 | if isinstance(node, ast.Call) and isinstance(node.func, ast.Name) and len(node.args) == 1 and isinstance(node.args[0], ast.Constant):
122 | if node.func.id == "collect_data_files" and node.args[0].value == "playwright":
123 | node.args[0].value = "patchright"
124 |
125 | patch_file("playwright-python/playwright/_impl/__pyinstaller/hook-playwright.sync_api.py", async_api_tree)
126 |
127 | # Patching playwright/_impl/_driver.py
128 | with open("playwright-python/playwright/_impl/_driver.py") as f:
129 | driver_source = f.read()
130 | driver_tree = ast.parse(driver_source)
131 |
132 | for node in ast.walk(driver_tree):
133 | if isinstance(node, ast.Call) and isinstance(node.func, ast.Attribute) and isinstance(node.func.value, ast.Name) and len(node.args) >= 1 and isinstance(node.args[0], ast.Name):
134 | if node.func.value.id == "inspect" and node.func.attr == "getfile" and node.args[0].id == "playwright":
135 | node.args[0].id = "patchright"
136 |
137 | patch_file("playwright-python/playwright/_impl/_driver.py", driver_tree)
138 |
139 | # Patching playwright/_impl/_connection.py
140 | with open("playwright-python/playwright/_impl/_connection.py") as f:
141 | connection_source = f.read()
142 | connection_source_tree = ast.parse(connection_source)
143 |
144 | for node in ast.walk(connection_source_tree):
145 | if isinstance(node, ast.Call) and isinstance(node.func, ast.Name) and len(node.args) >= 1 and isinstance(node.args[0], ast.Attribute):
146 | if node.func.id == "Path" and node.args[0].value.id == "playwright":
147 | node.args[0].value.id = "patchright"
148 |
149 | elif isinstance(node, ast.Attribute) and isinstance(node.value, ast.Attribute) and isinstance(node.value.value, ast.Attribute) and isinstance(node.value.value.value, ast.Name):
150 | if node.value.value.value.id == "playwright" and node.value.value.attr == "_impl" and node.value.attr == "_impl_to_api_mapping":
151 | node.value.value.value.id = "patchright"
152 |
153 | patch_file("playwright-python/playwright/_impl/_connection.py", connection_source_tree)
154 |
155 | # Patching playwright/_impl/_js_handle.py
156 | with open("playwright-python/playwright/_impl/_js_handle.py") as f:
157 | js_handle_source = f.read()
158 | js_handle_tree = ast.parse(js_handle_source)
159 |
160 | for node in ast.walk(js_handle_tree):
161 | if isinstance(node, ast.FunctionDef) and node.name == "add_source_url_to_script":
162 | for function_node in node.body:
163 | if isinstance(function_node, ast.Return):
164 | function_node.value = ast.Name(id="source", ctx=ast.Load())
165 |
166 | if isinstance(node, ast.AsyncFunctionDef) and node.name in ["evaluate", "evaluate_handle"]:
167 | node.args.kwonlyargs.append(ast.arg(
168 | arg="isolatedContext",
169 | annotation=ast.Subscript(
170 | value=ast.Name(id="Optional", ctx=ast.Load()),
171 | slice=ast.Name(id="bool", ctx=ast.Load()),
172 | ctx=ast.Load(),
173 | ),
174 | ))
175 | node.args.kw_defaults.append(ast.Constant(value=True))
176 |
177 | for subnode in ast.walk(node):
178 | if isinstance(subnode, ast.Return) and isinstance(subnode.value, ast.Call):
179 | if subnode.value.args and isinstance(subnode.value.args[0], ast.Await):
180 | inner_call = subnode.value.args[0].value
181 | if isinstance(inner_call, ast.Call) and inner_call.func.attr == "send":
182 | for i, arg in enumerate(inner_call.args):
183 | if isinstance(arg, ast.Call) and arg.func.id == "dict":
184 | arg.keywords.append(ast.keyword(
185 | arg="isolatedContext",
186 | value=ast.Name(id="isolatedContext", ctx=ast.Load())
187 | ))
188 |
189 | patch_file("playwright-python/playwright/_impl/_js_handle.py", js_handle_tree)
190 |
191 | # Patching playwright/_impl/_frame.py
192 | with open("playwright-python/playwright/_impl/_frame.py") as f:
193 | frame_source = f.read()
194 | frame_tree = ast.parse(frame_source)
195 |
196 | for node in ast.walk(frame_tree):
197 | if isinstance(node, ast.AsyncFunctionDef) and node.name in ["evaluate", "evaluate_handle", "eval_on_selector_all"]:
198 | node.args.kwonlyargs.append(ast.arg(
199 | arg="isolatedContext",
200 | annotation=ast.Subscript(
201 | value=ast.Name(id="Optional", ctx=ast.Load()),
202 | slice=ast.Name(id="bool", ctx=ast.Load()),
203 | ctx=ast.Load(),
204 | ),
205 | ))
206 | node.args.kw_defaults.append(ast.Constant(value=True))
207 |
208 | for subnode in ast.walk(node):
209 | if isinstance(subnode, ast.Return) and isinstance(subnode.value, ast.Call):
210 | if subnode.value.args and isinstance(subnode.value.args[0], ast.Await):
211 | inner_call = subnode.value.args[0].value
212 | if isinstance(inner_call, ast.Call) and inner_call.func.attr == "send":
213 | for i, arg in enumerate(inner_call.args):
214 | if isinstance(arg, ast.Call) and arg.func.id == "dict":
215 | arg.keywords.append(ast.keyword(
216 | arg="isolatedContext",
217 | value=ast.Name(id="isolatedContext", ctx=ast.Load())
218 | ))
219 |
220 | patch_file("playwright-python/playwright/_impl/_frame.py", frame_tree)
221 |
222 | # Patching playwright/_impl/_locator.py
223 | with open("playwright-python/playwright/_impl/_locator.py") as f:
224 | frame_source = f.read()
225 | frame_tree = ast.parse(frame_source)
226 |
227 | for node in ast.walk(frame_tree):
228 | if isinstance(node, ast.AsyncFunctionDef) and node.name in ["evaluate", "evaluate_handle", "evaluate_all"]:
229 | node.args.kwonlyargs.append(ast.arg(
230 | arg="isolatedContext",
231 | annotation=ast.Subscript(
232 | value=ast.Name(id="Optional", ctx=ast.Load()),
233 | slice=ast.Name(id="bool", ctx=ast.Load()),
234 | ctx=ast.Load(),
235 | ),
236 | ))
237 | node.args.kw_defaults.append(ast.Constant(value=True))
238 |
239 | for subnode in ast.walk(node):
240 | if isinstance(subnode, ast.Return) and isinstance(subnode.value, ast.Await):
241 | call_expr = subnode.value.value
242 | if isinstance(call_expr, ast.Call):
243 | if node.name in ["evaluate", "evaluate_handle"] and isinstance(call_expr.func, ast.Attribute):
244 | if call_expr.func.attr == "_with_element":
245 | if call_expr.args and isinstance(call_expr.args[0], ast.Lambda):
246 | lambda_func = call_expr.args[0].body
247 | if isinstance(lambda_func, ast.Call) and isinstance(lambda_func.func, ast.Attribute):
248 | if lambda_func.func.attr == node.name:
249 | lambda_func.keywords.append(ast.keyword(
250 | arg="isolatedContext",
251 | value=ast.Name(id="isolatedContext", ctx=ast.Load())
252 | ))
253 | elif call_expr.func.attr == "eval_on_selector_all":
254 | call_expr.keywords.append(ast.keyword(
255 | arg="isolatedContext",
256 | value=ast.Name(id="isolatedContext", ctx=ast.Load())
257 | ))
258 |
259 |
260 | patch_file("playwright-python/playwright/_impl/_locator.py", frame_tree)
261 |
262 | # Patching playwright/_impl/_browser_context.py
263 | with open("playwright-python/playwright/_impl/_browser_context.py") as f:
264 | browser_context_source = f.read()
265 | browser_context_tree = ast.parse(browser_context_source)
266 |
267 | for node in ast.walk(browser_context_tree):
268 | if isinstance(node, ast.ClassDef) and node.name == "BrowserContext":
269 | for class_node in node.body:
270 | if isinstance(class_node, ast.AsyncFunctionDef) and class_node.name == "add_init_script":
271 | class_node.body.insert(0, ast.parse("await self.install_inject_route()"))
272 | elif isinstance(class_node, ast.AsyncFunctionDef) and class_node.name == "expose_binding":
273 | class_node.body.insert(0, ast.parse("await self.install_inject_route()"))
274 |
275 | node.body.append(
276 | ast.Assign(
277 | targets=[ast.Name(id='route_injecting', ctx=ast.Store())],
278 | value=ast.Constant(value=False))
279 | )
280 |
281 | node.body.append(
282 | ast.parse("""\
283 | async def install_inject_route(self) -> None:
284 | from patchright._impl._impl_to_api_mapping import ImplToApiMapping
285 | mapping = ImplToApiMapping()
286 |
287 | async def route_handler(route: Route) -> None:
288 | try:
289 | if route.request.resource_type == "document" and route.request.url.startswith("http"):
290 | protocol = route.request.url.split(":")[0]
291 | await route.continue_(url=f"{protocol}://patchright-init-script-inject.internal/")
292 | else:
293 | await route.continue_()
294 | except:
295 | await route.continue_()
296 |
297 | if not self.route_injecting:
298 | if self._connection._is_sync:
299 | self._routes.insert(
300 | 0,
301 | RouteHandler(
302 | self._options.get("baseURL"),
303 | "**/*",
304 | mapping.wrap_handler(route_handler),
305 | False,
306 | None,
307 | ),
308 | )
309 | await self._update_interception_patterns()
310 | else:
311 | await self.route("**/*", mapping.wrap_handler(route_handler))
312 | self.route_injecting = True""").body[0])
313 |
314 | patch_file("playwright-python/playwright/_impl/_browser_context.py", browser_context_tree)
315 |
316 | # Patching playwright/_impl/_page.py
317 | with open("playwright-python/playwright/_impl/_page.py") as f:
318 | page_source = f.read()
319 | page_tree = ast.parse(page_source)
320 |
321 | for node in ast.walk(page_tree):
322 | if isinstance(node, ast.ClassDef) and node.name == "Page":
323 | for class_node in node.body:
324 | if isinstance(class_node, ast.AsyncFunctionDef) and class_node.name == "add_init_script":
325 | class_node.body.insert(0, ast.parse("await self.install_inject_route()"))
326 | elif isinstance(class_node, ast.AsyncFunctionDef) and class_node.name == "expose_binding":
327 | class_node.body.insert(0, ast.parse("await self.install_inject_route()"))
328 |
329 | node.body.append(
330 | ast.Assign(
331 | targets=[ast.Name(id='route_injecting', ctx=ast.Store())],
332 | value=ast.Constant(value=False))
333 | )
334 |
335 | node.body.append(
336 | ast.parse("""\
337 | async def install_inject_route(self) -> None:
338 | from patchright._impl._impl_to_api_mapping import ImplToApiMapping
339 | mapping = ImplToApiMapping()
340 |
341 | async def route_handler(route: Route) -> None:
342 | try:
343 | if route.request.resource_type == "document" and route.request.url.startswith("http"):
344 | protocol = route.request.url.split(":")[0]
345 | await route.continue_(url=f"{protocol}://patchright-init-script-inject.internal/")
346 | else:
347 | await route.continue_()
348 | except:
349 | await route.continue_()
350 |
351 | if not self.route_injecting and not self.context.route_injecting:
352 | if self._connection._is_sync:
353 | self._routes.insert(
354 | 0,
355 | RouteHandler(
356 | self._browser_context._options.get("baseURL"),
357 | "**/*",
358 | mapping.wrap_handler(route_handler),
359 | False,
360 | None,
361 | ),
362 | )
363 | await self._update_interception_patterns()
364 | else:
365 | await self.route("**/*", mapping.wrap_handler(route_handler))
366 | self.route_injecting = True""").body[0])
367 |
368 | if isinstance(node, ast.AsyncFunctionDef) and node.name in ["evaluate", "evaluate_handle"]:
369 | node.args.kwonlyargs.append(ast.arg(
370 | arg="isolatedContext",
371 | annotation=ast.Subscript(
372 | value=ast.Name(id="Optional", ctx=ast.Load()),
373 | slice=ast.Name(id="bool", ctx=ast.Load()),
374 | ctx=ast.Load(),
375 | ),
376 | ))
377 | node.args.kw_defaults.append(ast.Constant(value=True))
378 |
379 | if "evaluateExpression" in ast.unparse(node.body[0]):
380 | for subnode in ast.walk(node):
381 | if isinstance(subnode, ast.Return) and isinstance(subnode.value, ast.Call):
382 | if subnode.value.args and isinstance(subnode.value.args[0], ast.Await):
383 | inner_call = subnode.value.args[0].value
384 | if isinstance(inner_call, ast.Call) and inner_call.func.attr == "send":
385 | for i, arg in enumerate(inner_call.args):
386 | if isinstance(arg, ast.Call) and arg.func.id == "dict":
387 | arg.keywords.append(ast.keyword(
388 | arg="isolatedContext",
389 | value=ast.Name(id="isolatedContext", ctx=ast.Load())
390 | ))
391 | elif "_main_frame" in ast.unparse(node.body[0]):
392 | for subnode in ast.walk(node):
393 | if isinstance(subnode, ast.Return) and isinstance(subnode.value, ast.Await) and isinstance(subnode.value.value, ast.Call):
394 | subnode.value.value.keywords.append(ast.keyword(
395 | arg="isolatedContext",
396 | value=ast.Name(id="isolatedContext", ctx=ast.Load())
397 | ))
398 |
399 |
400 | patch_file("playwright-python/playwright/_impl/_page.py", page_tree)
401 |
402 | # Patching playwright/_impl/_clock.py
403 | with open("playwright-python/playwright/_impl/_clock.py") as f:
404 | clock_source = f.read()
405 | clock_tree = ast.parse(clock_source)
406 |
407 | for node in ast.walk(clock_tree):
408 | if isinstance(node, ast.ClassDef) and node.name == "Clock":
409 | for class_node in node.body:
410 | if isinstance(class_node, ast.AsyncFunctionDef) and class_node.name == "install":
411 | class_node.body.insert(0, ast.parse("await self._browser_context.install_inject_route()"))
412 |
413 | patch_file("playwright-python/playwright/_impl/_clock.py", clock_tree)
414 |
415 | # Patching playwright/async_api/_generated.py
416 | with open("playwright-python/playwright/async_api/_generated.py") as f:
417 | async_generated_source = f.read()
418 | async_generated_tree = ast.parse(async_generated_source)
419 |
420 | for class_node in ast.walk(async_generated_tree):
421 | if isinstance(class_node, ast.ClassDef) and class_node.name in ["Page", "Frame", "Worker", "Locator"]:
422 | for node in class_node.body:
423 | if isinstance(node, ast.AsyncFunctionDef) and (node.name in ["evaluate", "evaluate_handle"] or (class_node.name == "Locator" and node.name == "evaluate_all")): # , "evaluate_all"
424 | new_arg = ast.arg(arg="isolated_context", annotation=ast.Subscript(
425 | value=ast.Name(id="typing.Optional", ctx=ast.Load()),
426 | slice=ast.Name(id="bool", ctx=ast.Load()),
427 | ctx=ast.Load(),
428 | ))
429 | # Append the argument to kwonlyargs
430 | node.args.kwonlyargs.append(new_arg)
431 | node.args.kw_defaults.append(ast.Constant(value=True))
432 |
433 | # Modify the inner function call inside return statement
434 | for subnode in ast.walk(node):
435 | if isinstance(subnode, ast.Call) and subnode.func.attr == node.name:
436 | subnode.keywords.append(
437 | ast.keyword(arg="isolatedContext",
438 | value=ast.Name(id="isolated_context",
439 | ctx=ast.Load())
440 | )
441 | )
442 |
443 | patch_file("playwright-python/playwright/async_api/_generated.py", async_generated_tree)
444 |
445 | # Patching playwright/sync_api/_generated.py
446 | with open("playwright-python/playwright/sync_api/_generated.py") as f:
447 | async_generated_source = f.read()
448 | async_generated_tree = ast.parse(async_generated_source)
449 |
450 | for class_node in ast.walk(async_generated_tree):
451 | if isinstance(class_node, ast.ClassDef) and class_node.name in ["Page", "Frame", "Worker", "Locator"]:
452 | for node in class_node.body:
453 | if isinstance(node, ast.FunctionDef) and (node.name in ["evaluate", "evaluate_handle"] or (class_node.name == "Locator" and node.name == "evaluate_all")): # , "evaluate_all"
454 | new_arg = ast.arg(arg="isolated_context", annotation=ast.Subscript(
455 | value=ast.Name(id="typing.Optional", ctx=ast.Load()),
456 | slice=ast.Name(id="bool", ctx=ast.Load()),
457 | ctx=ast.Load(),
458 | ))
459 | # Append the argument to kwonlyargs
460 | node.args.kwonlyargs.append(new_arg)
461 | node.args.kw_defaults.append(ast.Constant(value=True))
462 |
463 | # Modify the inner function call inside return statement
464 | for subnode in ast.walk(node):
465 | if isinstance(subnode, ast.Call) and subnode.func.attr == node.name:
466 | subnode.keywords.append(
467 | ast.keyword(arg="isolatedContext",
468 | value=ast.Name(id="isolated_context",
469 | ctx=ast.Load())
470 | )
471 | )
472 |
473 | patch_file("playwright-python/playwright/sync_api/_generated.py", async_generated_tree)
474 |
475 | # Patching Imports of every python file under the playwright-python/playwright directory
476 | for python_file in glob.glob("playwright-python/playwright/**.py") + glob.glob("playwright-python/playwright/**/**.py"):
477 | with open(python_file) as f:
478 | file_source = f.read()
479 | file_tree = ast.parse(file_source)
480 | renamed_attributes = []
481 |
482 | for node in ast.walk(file_tree):
483 | if isinstance(node, ast.Import):
484 | for alias in node.names:
485 | if alias.name.startswith("playwright"):
486 | if "__init__" in python_file:
487 | renamed_attributes.append(alias.name)
488 | alias.name = alias.name.replace("playwright", "patchright", 1)
489 | if isinstance(node, ast.ImportFrom) and node.module.startswith("playwright"):
490 | node.module = node.module.replace("playwright", "patchright", 1)
491 | if renamed_attributes and isinstance(node, ast.Attribute):
492 | unparsed_attribute = ast.unparse(node.value)
493 | if unparsed_attribute in renamed_attributes:
494 | node.value = ast.parse(unparsed_attribute.replace("playwright", "patchright", 1)).body[0].value
495 |
496 | patch_file(python_file, file_tree)
497 |
498 | # Rename the Package Folder to Patchright
499 | os.rename("playwright-python/playwright", "playwright-python/patchright")
500 |
501 | # Write the Projects README to the README which is used in the release
502 | with open("README.md", 'r') as src:
503 | with open("playwright-python/README.md", 'w') as dst:
504 | # Read from the source readme and write to the destination readme
505 | dst.write(src.read())
506 |
--------------------------------------------------------------------------------
/pyproject.toml:
--------------------------------------------------------------------------------
1 | # Only for test Runs
2 | [tool.pytest.ini_options]
3 | addopts = "-Wall -rsx" # -s
4 | markers = [
5 | "skip_browser",
6 | "only_browser",
7 | "skip_platform",
8 | "only_platform"
9 | ]
10 | junit_family = "xunit2"
11 | asyncio_mode = "auto"
12 | asyncio_default_fixture_loop_scope = "session"
13 | asyncio_default_test_loop_scope = "session"
14 |
--------------------------------------------------------------------------------
/utils/modify_tests.py:
--------------------------------------------------------------------------------
1 | import os
2 | import ast
3 | import itertools
4 |
5 | files_to_skip = [
6 | # Console Domain Disabled
7 | 'test_console.py',
8 |
9 | # query_selector is deprecated
10 | 'test_queryselector.py',
11 | 'test_element_handle.py',
12 | 'test_element_handle_wait_for_element_state.py',
13 |
14 | # https://github.com/Kaliiiiiiiiii-Vinyzu/patchright/issues/31
15 | 'test_route_web_socket.py'
16 | ]
17 |
18 | tests_to_skip = [
19 | # Disabled Console Domain
20 | "test_block_blocks_service_worker_registration",
21 | "test_console_event_should_work",
22 | "test_console_event_should_work_in_popup",
23 | "test_console_event_should_work_in_popup_2",
24 | "test_console_event_should_work_in_immediately_closed_popup",
25 | "test_dialog_event_should_work_in_immdiately_closed_popup",
26 | "test_console_event_should_work_with_context_manager",
27 | "test_weberror_event_should_work",
28 | "test_console_repr",
29 | "test_console_should_work",
30 | "test_should_collect_trace_with_resources_but_no_js",
31 | "test_should_work_with_playwright_context_managers",
32 | "test_should_respect_traces_dir_and_name",
33 | "test_should_show_tracing_group_in_action_list",
34 | "test_page_error_event_should_work",
35 | "test_click_offscreen_buttons",
36 | "test_watch_position_should_be_notified",
37 | "test_page_error_should_fire",
38 | "test_page_error_should_handle_odd_values",
39 | "test_page_error_should_handle_object",
40 | "test_page_error_should_handle_window",
41 | "test_page_error_should_pass_error_name_property",
42 | "test_workers_should_report_console_logs",
43 | "test_workers_should_have_JSHandles_for_console_logs",
44 | "test_workers_should_report_errors",
45 |
46 | # InitScript Timing
47 | "test_expose_function_should_be_callable_from_inside_add_init_script",
48 | "test_expose_bindinghandle_should_work",
49 | "test_browser_context_add_init_script_should_apply_to_an_in_process_popup",
50 | "test_should_expose_function_from_browser_context",
51 |
52 | # Disable Popup Blocking
53 | "test_page_event_should_have_an_opener",
54 |
55 | # query_selector is deprecated
56 | "test_should_work_with_layout_selectors",
57 | "test_should_dispatch_click_event_element_handle",
58 | "test_should_dispatch_drag_and_drop_events_element_handle",
59 |
60 | # Minor Differences in Call Log. Deemed Unimportant
61 | "test_should_be_attached_fail_with_not",
62 | "test_add_script_tag_should_include_source_url_when_path_is_provided",
63 |
64 | # Server/Client Header Mismatch
65 | "test_should_report_request_headers_array",
66 | "test_request_headers_should_get_the_same_headers_as_the_server_cors",
67 | "test_request_headers_should_get_the_same_headers_as_the_server",
68 | ]
69 |
70 | dont_isolate_evaluation_tests = [
71 | "test_timeout_waiting_for_stable_position",
72 | "test_jshandle_evaluate_accept_object_handle_as_argument",
73 | "test_jshandle_evaluate_accept_nested_handle",
74 | "test_jshandle_evaluate_accept_nested_window_handle",
75 | "test_jshandle_evaluate_accept_multiple_nested_handles",
76 | "test_should_dispatch_drag_drop_events",
77 | "test_should_dispatch_drag_and_drop_events_element_handle",
78 | "track_events",
79 | "captureLastKeydown",
80 | "test_expose_function_should_work_on_frames_before_navigation",
81 | ]
82 |
83 | # Reason for skipping tests_backup
84 | skip_reason = "Skipped as per documentation (https://github.com/Kaliiiiiiiiii-Vinyzu/patchright/issues/31)"
85 |
86 |
87 | class ParentAnnotator(ast.NodeVisitor):
88 | def __init__(self):
89 | self.parents = {}
90 |
91 | def visit(self, node):
92 | for child in ast.iter_child_nodes(node):
93 | self.parents[child] = node
94 | self.visit(child)
95 |
96 | def process_file(file_path):
97 | with open(file_path, 'r', encoding='utf-8') as f:
98 | source = f.read()
99 |
100 | file_tree = ast.parse(source)
101 | annotator = ParentAnnotator()
102 | annotator.visit(file_tree)
103 |
104 | for node in ast.walk(file_tree):
105 | # Rename Playwright Imports to Patchright
106 | if isinstance(node, ast.Import):
107 | for alias in node.names:
108 | if alias.name.startswith("playwright"):
109 | alias.name = alias.name.replace("playwright", "patchright", 1)
110 | if isinstance(node, ast.ImportFrom) and node.module.startswith("playwright"):
111 | node.module = node.module.replace("playwright", "patchright", 1)
112 |
113 | # Skip Tests Documented: https://github.com/Kaliiiiiiiiii-Vinyzu/patchright/issues/31
114 | if isinstance(node, ast.FunctionDef) or isinstance(node, ast.AsyncFunctionDef):
115 | # Add Server Arg to test_add_init_script Tests
116 | if "test_add_init_script" in file_path:
117 | node.args.args.append(ast.arg(arg='server', annotation=None))
118 | # Skip Tests to skip
119 | if node.name in tests_to_skip:
120 | skip_decorator = ast.parse(f"@pytest.mark.skip(reason='{skip_reason}')\ndef placeholder(): return").body[0].decorator_list[0]
121 | node.decorator_list.insert(0, skip_decorator)
122 |
123 | # Add isolated_context=False to every necessary evaluate/evaluate_handle Call
124 | if isinstance(node, ast.Call) and isinstance(node.func, ast.Attribute):
125 | # Very Bad Hack to get the parent node
126 | test_name = ""
127 | current_node = node
128 | while annotator.parents.get(current_node):
129 | current_node = annotator.parents[current_node]
130 | if isinstance(current_node, ast.FunctionDef) or isinstance(current_node, ast.AsyncFunctionDef):
131 | test_name = current_node.name
132 |
133 | if test_name in dont_isolate_evaluation_tests:
134 | # Don't add isolated_context=False to these tests
135 | continue
136 |
137 | if node.func.attr in ("evaluate", "evaluate_handle", "evaluate_all") and isinstance(node.func.value, ast.Name) and node.func.value.id in ("page", "popup", "button", "new_page", "page1", "page2", "target", "page_1", "page_2", "frame"):
138 | node.keywords.append(ast.keyword(arg='isolated_context', value=ast.Constant(value=False)))
139 |
140 | modified_source = ast.unparse(ast.fix_missing_locations(file_tree))
141 |
142 | with open(file_path, 'w', encoding='utf-8') as f:
143 | f.write(modified_source)
144 |
145 | def main():
146 | with open("./tests/assets/inject.html", "w") as f:
147 | f.write("")
148 |
149 | with open("./tests/conftest.py", "r") as read_f:
150 | conftest_content = read_f.read()
151 | updated_conftest_content = conftest_content.replace(
152 | "Path(inspect.getfile(playwright)).parent",
153 | "Path(inspect.getfile(patchright)).parent"
154 | )
155 |
156 | with open("./tests/conftest.py", "w") as write_f:
157 | write_f.write(updated_conftest_content)
158 |
159 |
160 | for root, _, files in os.walk("tests"):
161 | for file in files:
162 | file_path = os.path.join(root, file)
163 |
164 | # Init Script Behaviour https://github.com/Kaliiiiiiiiii-Vinyzu/patchright/issues/30
165 | if file == "test_add_init_script.py":
166 | with open(file_path, 'r', encoding='utf-8') as f:
167 | content = f.read()
168 |
169 | # Replace the full quoted strings with valid Python expressions (not strings)
170 | content = content.replace(
171 | '"data:text/html,"',
172 | 'server.PREFIX + "/inject.html"'
173 | ).replace(
174 | '"data:text/html,"',
175 | 'server.PREFIX + "/empty.html"'
176 | )
177 |
178 | with open(file_path, 'w', encoding='utf-8') as f:
179 | f.write(content)
180 |
181 | # Init Script Behaviour https://github.com/Kaliiiiiiiiii-Vinyzu/patchright/issues/30
182 | if file == "test_page_clock.py":
183 | with open(file_path, 'r', encoding='utf-8') as f:
184 | content = f.read()
185 |
186 | # Replace the full quoted strings with valid Python expressions (not strings)
187 | content = content.replace(
188 | "about:blank",
189 | "https://www.google.com/blank.html"
190 | ).replace(
191 | "data:text/html,",
192 | "https://www.google.com/blank.html"
193 | )
194 |
195 | with open(file_path, 'w', encoding='utf-8') as f:
196 | f.write(content)
197 |
198 | # Import Pytest
199 | if file in ("test_browsercontext_service_worker_policy.py", "test_tracing.py", "test_popup.py", "test_dispatch_event.py"):
200 | # Append "import pytest" to the top of the file
201 | with open(file_path, 'r+', encoding='utf-8') as f:
202 | content = f.read()
203 | if "import pytest" not in content:
204 | f.seek(0, 0)
205 | f.write("import pytest\n" + content)
206 |
207 | # Skipping Files
208 | if file in files_to_skip:
209 | # Delete File
210 | os.remove(file_path)
211 | continue
212 |
213 | if file.endswith('.py'):
214 | process_file(file_path)
215 |
216 | if __name__ == '__main__':
217 | main()
--------------------------------------------------------------------------------
/utils/release_version_check.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 |
3 | # Function to get the latest release version from a GitHub repository
4 | get_latest_release() {
5 | local repo=$1
6 | local response=$(curl --silent "https://api.github.com/repos/$repo/releases/latest")
7 | local version=$(echo "$response" | grep '"tag_name"' | sed -E 's/.*"([^"]+)".*/\1/')
8 |
9 | # Check if version is empty (meaning no releases found)
10 | if [ -z "$version" ]; then
11 | version="v0.0.0"
12 | fi
13 |
14 | echo "$version"
15 | }
16 |
17 | # Function to compare two semantic versions (ignoring 'v' prefix)
18 | version_is_behind() {
19 | local version1=${1//v/} # Remove 'v' prefix from version1
20 | local version2=${2//v/} # Remove 'v' prefix from version2
21 |
22 | IFS='.' read ver1_1 ver1_2 ver1_3 <<< "$version1"
23 | IFS='.' read ver2_1 ver2_2 ver2_3 <<< "$version2"
24 |
25 | ver1_1=${ver1_1:-0}
26 | ver1_2=${ver1_2:-0}
27 | ver1_3=${ver1_3:-0}
28 | ver2_1=${ver2_1:-0}
29 | ver2_2=${ver2_2:-0}
30 | ver2_3=${ver2_3:-0}
31 |
32 | if ((10#$ver1_1 < 10#$ver2_1)) || ((10#$ver1_1 == 10#$ver2_1 && 10#$ver1_2 < 10#$ver2_2)) || ((10#$ver1_1 == 10#$ver2_1 && 10#$ver1_2 == 10#$ver2_2 && 10#$ver1_3 < 10#$ver2_3)); then
33 | return 0
34 | else
35 | return 1
36 | fi
37 | }
38 |
39 | # Get the latest release version of microsoft/playwright-python
40 | playwright_version=$(get_latest_release "microsoft/playwright-python")
41 | echo "Latest release of the Playwright-Python: $playwright_version"
42 |
43 | # Get the latest release version of Patchright
44 | patchright_version=$(get_latest_release $REPO)
45 | echo "Latest release of the Patchright-Python: $patchright_version"
46 |
47 | # Compare the versions
48 | if version_is_behind "$patchright_version" "$playwright_version"; then
49 | echo "$REPO is behind microsoft/playwright-python. Building & Patching..."
50 | echo "proceed=true" >>$GITHUB_OUTPUT
51 | echo "playwright_version=$playwright_version" >>$GITHUB_ENV
52 | else
53 | echo "$REPO is up to date with microsoft/playwright-python."
54 | echo "proceed=false" >>$GITHUB_OUTPUT
55 | fi
56 |
--------------------------------------------------------------------------------