This commit is contained in:
steven 2025-08-11 22:23:30 +02:00
commit 72a26edcff
22092 changed files with 2101903 additions and 0 deletions

15
lib/sc/.editorconfig Normal file
View file

@ -0,0 +1,15 @@
; This file is for unifying the coding style for different editors and IDEs.
; More information at http://editorconfig.org
root = true
[*]
charset = utf-8
indent_size = 4
indent_style = space
end_of_line = lf
insert_final_newline = true
trim_trailing_whitespace = true
[*.md]
trim_trailing_whitespace = false

2
lib/sc/.github/FUNDING.yml vendored Normal file
View file

@ -0,0 +1,2 @@
github: spekulatius
custom: https://phpscraper.de/misc/sponsors.html

85
lib/sc/.github/workflows/test.yaml vendored Normal file
View file

@ -0,0 +1,85 @@
on: [pull_request]
jobs:
phpunit:
name: PHPUnit
runs-on: ubuntu-latest
strategy:
matrix:
php-version: ['8.1', '8.2', '8.3']
steps:
- uses: actions/checkout@v4
- uses: shivammathur/setup-php@v2
with:
php-version: ${{ matrix.php-version }}
coverage: none
extensions: intl curl
- run: composer update --no-interaction --no-progress --prefer-dist --ansi
- run: composer test:unit
phpstan:
name: PHPStan
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Install PHP
uses: shivammathur/setup-php@v2
with:
php-version: '8.1'
coverage: none
env:
COMPOSER_TOKEN: ${{ github.token }}
update: true
- name: Install dependencies
run: composer update --prefer-dist --no-interaction --no-progress --optimize-autoloader
- name: PHPStan tests
run: composer test:types
rector:
name: Rector
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Install PHP
uses: shivammathur/setup-php@v2
with:
php-version: '8.1'
coverage: none
env:
COMPOSER_TOKEN: ${{ github.token }}
update: true
- name: Install dependencies
run: composer update --prefer-dist --no-interaction --no-progress --optimize-autoloader
- name: PHPStan tests
run: composer test:refactor
pint:
name: Pint
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Install PHP
uses: shivammathur/setup-php@v2
with:
php-version: '8.1'
coverage: none
tools: cs2pr
env:
COMPOSER_TOKEN: ${{ github.token }}
update: true
- name: Install dependencies
run: composer update --prefer-dist --no-interaction --no-progress --optimize-autoloader
- name: Run Pint
run: composer exec -- pint --test --format=checkstyle | cs2pr

12
lib/sc/.gitignore vendored Normal file
View file

@ -0,0 +1,12 @@
vendor
.idea
.php_cs.cache
.phpunit.result.cache
composer.lock
yarn-error.log
websites/.yarn/
websites/.yarnrc.yml
.vscode
.history
.notes
.tmp/

97
lib/sc/CHANGELOG.md Normal file
View file

@ -0,0 +1,97 @@
# PHPScraper CHANGELOG
All notable changes to this project will be documented in this file.
Parts regarding the [documentation website](https://phpscraper.de), the [test pages](https://github.com/spekulatius/phpscraper-test-pages) and individual documentation changes are omitted for better readability.
This project adheres to [Semantic Versioning](http://semver.org/).
## 2.0.0 (2023-06-01)
- [#187](https://github.com/spekulatius/PHPScraper/issues/187): Prepare v2: Improve typing, bringing PHPStan to --level=9. For details check the [CHANGELOG](https://github.com/spekulatius/PHPScraper/blob/master/UPGRADING.md#from-1x-to-2x).
- [#188](https://github.com/spekulatius/PHPScraper/issues/188): Support PHPStan for Windows Users
- [#185](https://github.com/spekulatius/PHPScraper/issues/185): Adding PHP 8.3 to test pipeline
- [#184](https://github.com/spekulatius/PHPScraper/issues/184): Adding PHPStan GitHub Action. Thank you @nadar!
- [#183](https://github.com/spekulatius/PHPScraper/issues/183): Switch from Goutte to BrowserKit
- [#182](https://github.com/spekulatius/PHPScraper/issues/182): Drop PHP 7.3 and 7.4
- [#174](https://github.com/spekulatius/PHPScraper/issues/174): Fix local testing
- [#173](https://github.com/spekulatius/PHPScraper/issues/173): Fix README example
- [#171](https://github.com/spekulatius/PHPScraper/issues/171): Various PHPStan improvements
- [#169](https://github.com/spekulatius/PHPScraper/issues/169): Adding `<meta charset=...>` extraction
## 1.0.2 (2022-12-15)
- [#167](https://github.com/spekulatius/PHPScraper/issues/167): Updating CHANGELOG.md
- [#166](https://github.com/spekulatius/PHPScraper/issues/166): Minor tidy ups in comments
- [#165](https://github.com/spekulatius/PHPScraper/issues/165): Adding PHP 8.2 to test workflow
- [#160](https://github.com/spekulatius/PHPScraper/issues/160): Allow complete interface for HttpClient instead of only one class.
## 1.0.1 (2022-12-02)
- [#156](https://github.com/spekulatius/PHPScraper/issues/156): Tidy up: Make file naming more intuitive and fix comments
- [#154](https://github.com/spekulatius/PHPScraper/issues/154): Expose GoutteClient as an accessible property
## 1.0.0 (2022-11-24)
- [#151](https://github.com/spekulatius/PHPScraper/issues/151): Migrate website into separate repo.
- [#150](https://github.com/spekulatius/PHPScraper/issues/150): Switch namespaces. See [UPGRADING](https://github.com/spekulatius/PHPScraper/blob/master/UPGRADING.md) for more details.
- [#147](https://github.com/spekulatius/PHPScraper/issues/147): Prepare for v1.0
## 0.13.0 (2022-11-21)
- [#146](https://github.com/spekulatius/PHPScraper/issues/146): Implement plain text file/URL parsing.
## 0.12.0 (2022-11-10)
- [#142](https://github.com/spekulatius/PHPScraper/issues/142): Implement feed parsing.
- [#145](https://github.com/spekulatius/PHPScraper/issues/145): Re-enable previously deactivated tests
## 0.11.0 (2022-11-01)
- [#137](https://github.com/spekulatius/PHPScraper/issues/137): Fix download bug and improve testing
## 0.10.0 (2022-11-01)
- [#136](https://github.com/spekulatius/PHPScraper/issues/136): Expand set of URL-related methods
## 0.9.0 (2022-10-28)
- [#79](https://github.com/spekulatius/PHPScraper/issues/79): Replace URL lib. Sub-domain support dropped.
## 0.8.0 (2022-10-27)
- Maintenance: [Split Core lib](https://github.com/spekulatius/PHPScraper/commit/2ca34caae75e634442daf9c4f886060e41ba8911) for better understandably.
## 0.7.0 (2022-10-14)
- [Generalize Configuration API](https://github.com/spekulatius/PHPScraper/commit/e19baeb19658fbc4846c24eb597876f54c6012a3) for better usability.
- [Proxy Support](https://github.com/spekulatius/PHPScraper/commit/326bdff4430a326bdb08f6af8452f148250c7784)
## 0.6.0 (2022-07-14)
- [#77](https://github.com/spekulatius/PHPScraper/issues/77): Upgrade to allow Symfony 6
## 0.5.0 (2022-08-16)
- Add [`rel`-interpretation](https://github.com/spekulatius/PHPScraper/commit/47d6f8a0f6adf49de31b691b98ea472a4a382b9f) to link methods.
- Add support to BYO-HTML: [`setContent`](https://github.com/spekulatius/PHPScraper/commit/9c50d145f280732e26ecf83c8d2978c07466dfcd).
- Improve typing support
- [Add Lists](https://github.com/spekulatius/PHPScraper/commit/0aac52853ab394d9f38b004e401c5fbec328e017)
## 0.4.0 (2022-08-16)
- Add [keyword scoring](https://github.com/spekulatius/PHPScraper/commit/e91bce24e4b53d9a1ef19b3f1ded97627eb2076e) in.
## 0.3.0 (2022-06-20)
- Add [keyword extraction](https://github.com/spekulatius/PHPScraper/commit/9d20004ead5b9e8350a03fa6fc4de1477b19bd4c) lib in.
## 0.2.0 (2022-06-20)
- Adding [support for `internalLinks` & `externalLinks`](https://github.com/spekulatius/PHPScraper/commit/193f422f206b7a10586463fff4a7f9dcc9e896f9).
## 0.1.0 (2022-05-04)
- Start testing using PHPUnit.
- Drop keeping own copy of current URL.
- Initial commit with basics functionality.

28
lib/sc/CONTRIBUTING.md Normal file
View file

@ -0,0 +1,28 @@
# Contribution Guide
This page contains guidelines for contributing to the this project. Please
review these guidelines before submitting any pull requests.
## Pull Requests
The pull request process differs for new features and bugs. Before sending a
pull request for a new feature, you should first create an issue with
`[Proposal]` in the title. The proposal should describe the new feature, as well
as implementation ideas. The proposal will then be reviewed and either approved
or denied. Once a proposal is approved, a pull request may be created
implementing the new feature. Pull requests which do not follow this guideline
will be closed immediately.
Pull requests for bugs may be sent without creating any proposal issue. If you
believe that you know of a solution for a bug that has been filed on GitHub,
please leave a comment detailing your proposed fix.
### Feature Requests
If you have an idea for a new feature you would like to see added, you may
create an issue on GitHub with `[Request]` in the title. The feature request
will then be reviewed.
## Coding Guidelines
This project follows the PSR-0, PSR-1, and PSR-2 coding standards.

674
lib/sc/LICENSE.md Normal file
View file

@ -0,0 +1,674 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
PHPScraper is a web-page parsing interface around Goutte (itself licensed under MIT).
Copyright (C) 2020 Peter Thaleikis
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
PHPScraper Copyright (C) 2020 Peter Thaleikis
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<https://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>.

325
lib/sc/README.md Normal file
View file

@ -0,0 +1,325 @@
<p align="center">
<a href="https://github.com/spekulatius/PHPScraper">
<picture style="width: 100%;" alt="PHP Scraper: a web utility for PHP">
<source srcset="https://github.com/spekulatius/phpscraper-docs/blob/master/.vuepress/public/logo-dark.png" media="(prefers-color-scheme:dark)">
<img src="https://github.com/spekulatius/phpscraper-docs/blob/master/.vuepress/public/logo-light.png" alt="PHP Scraper: a web utility for PHP">
</picture>
</a>
<p align="center">
<a href="https://github.com/spekulatius/PHPScraper/actions/workflows/test.yaml">
<img src="https://github.com/spekulatius/PHPScraper/actions/workflows/test.yaml/badge.svg" alt="Unit Tests">
</a>
<a href="https://packagist.org/packages/spekulatius/PHPScraper">
<img src="https://poser.pugx.org/spekulatius/PHPScraper/d/total.svg" alt="Total Downloads">
</a>
<a href="https://packagist.org/packages/spekulatius/PHPScraper">
<img src="https://poser.pugx.org/spekulatius/PHPScraper/v/stable.svg" alt="Latest Version">
</a>
<a href="https://packagist.org/packages/spekulatius/PHPScraper">
<img src="https://poser.pugx.org/spekulatius/PHPScraper/license.svg" alt="License">
</a>
</p>
<p align="center">
<strong>For full documentation, visit <a href="https://phpscraper.de">phpscraper.de</a></strong>.
</p>
</p>
PHPScraper is a versatile web-utility for PHP. Its primary objective is to streamline the process of extracting information from websites, allowing you to focus on accomplishing tasks without getting caught up in the complexities of selectors, data structure preparation, and conversion.
Under the hood, it uses
- [BrowserKit](https://symfony.com/doc/current/components/browser_kit.html) (formerly [Goutte](https://github.com/FriendsOfPHP/Goutte)) to access the web
- [League/URI](https://github.com/thephpleague/uri) to process URLs
- [donatello-za/rake-php-plus](https://github.com/donatello-za/rake-php-plus) to extract and analyze keywords
See [composer.json](https://github.com/spekulatius/PHPScraper/blob/master/composer.json) for more details.
:timer_clock: PHPScraper in 5 Minutes explained
-----------------------------------------------
Here are a few impressions of the way the library works. More examples are on the [project website](https://phpscraper.de/examples/scrape-website-title.html).
### Basics: Flexible Calling as an Attribute or Method
All scraping functionality can be accessed either as a function call or a property call. For example, the title can be accessed in two ways:
```php
// Prep
$web = new \Spekulatius\PHPScraper\PHPScraper;
$web->go('https://google.com');
// Returns "Google"
echo $web->title;
// Also returns "Google"
echo $web->title();
```
### :battery: Batteries included: Meta data, Links, Images, Headings, Content, Keywords, ...
Many common use cases are covered already. You can find prepared extractors for various HTML tags, including interesting attributes. You can filter and combine these to your needs. In some cases there is an option to get a simple or detailed version, here in the case of `linksWithDetails`:
```PHP
$web = new \Spekulatius\PHPScraper\PHPScraper;
// Contains:
// <a href="https://placekitten.com/456/500" rel="ugc">
// <img src="https://placekitten.com/456/400">
// <img src="https://placekitten.com/456/300">
// </a>
$web->go('https://test-pages.phpscraper.de/links/image-urls.html');
// Get the first link on the page and print the result
print_r($web->linksWithDetails[0]);
// [
// 'url' => 'https://placekitten.com/456/500',
// 'protocol' => 'https',
// 'text' => '',
// 'title' => null,
// 'target' => null,
// 'rel' => 'ugc',
// 'image' => [
// 'https://placekitten.com/456/400',
// 'https://placekitten.com/456/300'
// ],
// 'isNofollow' => false,
// 'isUGC' => true,
// 'isSponsored' => false,
// 'isMe' => false,
// 'isNoopener' => false,
// 'isNoreferrer' => false,
// ]
```
If there aren't any matching elements (here links) on the page, an empty array will be returned. If a method normally returns a string it might return `null`. Details such as `follow_redirects`, etc. are optional configuration parameters (see below).
Most of the DOM should be covered using these methods:
- several [meta-tags](https://phpscraper.de/examples/scrape-meta-tags.html) and other [`<head>`-information](https://phpscraper.de/examples/scrape-header-tags.html)
- [Social-Media information](https://phpscraper.de/examples/scrape-social-media-meta-tags.html) like Twitter Card and Facebook Open Graph
- Content: [Headings](https://phpscraper.de/examples/headings.html), [Outline](https://phpscraper.de/examples/outline.html), [Texts](https://phpscraper.de/examples/paragraphs.html) and [Lists](https://phpscraper.de/examples/lists.html)
- [Images](https://phpscraper.de/examples/scrape-images.html)
- [Links](https://phpscraper.de/examples/scrape-links.html)
- [Keywords](https://phpscraper.de/examples/extract-keywords.html)
**A full list of methods with example code can be found on [phpscraper.de](https://phpscraper.de). Further examples are in the [tests](https://github.com/spekulatius/PHPScraper/tree/master/tests).**
### Download Files
Besides processing the content on the page itself, you can download files using `fetchAsset`:
```php
// Absolute URL
$csvString = $web->fetchAsset('https://test-pages.phpscraper.de/test.csv');
// Relative URL after navigation
$csvString = $web
->go('https://test-pages.phpscraper.de/meta/lorem-ipsum.html')
->fetchAsset('/test.csv');
```
You will only need to write the content into a file or cloud storage.
### Process the RSS feeds, `sitemap.xml`, etc.
PHPScraper can assist in collecting feeds such as [RSS feeds, `sitemap.xml`-entries and static search indexes](https://phpscraper.de/examples/scrape-feeds.html). This can be useful when deciding on the next page to crawl or building up a list of pages on a website.
Here we are processing the sitemap into a set of [`FeedEntry`-DTOs](https://github.com/spekulatius/PHPScraper/blob/master/src/DataTransferObjects/FeedEntry.php):
```php
(new \Spekulatius\PHPScraper\PHPScraper)
->go('https://phpscraper.de')
->sitemap
// array(131) {
// [0]=>
// object(Spekulatius\PHPScraper\DataTransferObjects\FeedEntry)#165 (3) {
// ["title"]=>
// string(0) ""
// ["description"]=>
// string(0) ""
// ["link"]=>
// string(22) "https://phpscraper.de/"
// }
// [1]=>
// ...
```
Whenever post-processing is applied, you can fall back to the underlying `*Raw`-methods.
### Process CSV-, XML- and JSON files and URLs
PHPScraper comes out of the box with file / URL processing methods for CSV-, XML- and JSON:
- `parseJson`
- `parseXml`
- `parseCsv`
- `parseCsvWithHeader` (generates an asso. array using the first row)
Each method can process both strings as well as URLs:
```php
// Parse JSON into array:
$json = $web->parseJson('[{"title": "PHP Scraper: a web utility for PHP", "url": "https://phpscraper.de"}]');
// [
// 'title' => 'PHP Scraper: a web utility for PHP',
// 'url' => 'https://phpscraper.de'
// ]
// Fetch and parse CSV into a simple array:
$csv = $web->parseCsv('https://test-pages.phpscraper.de/test.csv');
// [
// ['date', 'value'],
// ['1945-02-06', 4.20],
// ['1952-03-11', 42],
// ]
// Fetch and parse CSV with first row as header into an asso. array structure:
$csv = $web->parseCsvWithHeader('https://test-pages.phpscraper.de/test.csv');
// [
// ['date' => '1945-02-06', 'value' => 4.20],
// ['date' => '1952-03-11', 'value' => 42],
// ]
```
Additional CSV parsing parameters such as separator, enclosure and escape are possible.
### There is more!
There are plenty of examples on the [PHPScraper website](https://phpscraper.de) and in the [tests](https://github.com/spekulatius/PHPScraper/tree/master/tests).
Check the [`playground.php`](https://github.com/spekulatius/PHPScraper/blob/master/playground.php) if you prefer learning by doing. You get it up and running with:
```bash
$ git clone git@github.com:spekulatius/PHPScraper.git && composer update
```
:muscle: Roadmap
----------------
The future development is organized into [milestones](https://github.com/spekulatius/PHPScraper/milestones?direction=asc&sort=title). Releases follow [semver](https://semver.org/).
### v1: [Building the first stable version](https://github.com/spekulatius/PHPScraper/milestone/4?closed=1)
- Improve documentation and examples.
- Organize code better (move websites into separate repos, etc.)
- Add support for feeds and some typical file types.
### v2: Service Upgrade:
- Switch from Goutte to [Symfony BrowserKit](https://symfony.com/doc/current/components/browser_kit.html). Goutte has been archived.
### v3: [Expand the functionality and cover more 'types'](https://github.com/spekulatius/PHPScraper/milestone/5)
- Expand to parse a wider range of types, elements, embeds, etc.
- Improve performance with caching and concurrent fetching of assets
- Minor improvements for parsing methods
### v4: [Expand to provide more guidance on building custom scrapers on top of PHPScraper](https://github.com/spekulatius/PHPScraper/milestone/6)
TBC.
:heart_eyes: Sponsors
---------------------
PHPScraper is sponsored by:
<a href="https://bringyourownideas.com" target="_blank" rel="noopener noreferrer"><img src="https://bringyourownideas.com/images/byoi-logo.jpg" height="100px"></a>
With your support, PHPScraper can became the *PHP swiss army knife for the web*. If you find PHPScraper useful to your work, please consider a [sponsorship](https://github.com/sponsors/spekulatius) or [donation](https://www.buymeacoffee.com/spekulatius). Thank you :muscle:
:gear: Configuration (optional)
-------------------------------
If needed, you can use the following configuration options:
### User Agent
You can set the browser agent using `setConfig`:
```php
$web->setConfig([
'agent' => 'Mozilla/5.0 (X11; Linux x86_64; rv:107.0) Gecko/20100101 Firefox/107.0'
]);
```
It defaults to `Mozilla/5.0 (compatible; PHP Scraper/1.x; +https://phpscraper.de)`.
### Proxy Support
You can configure proxy support with `setConfig`:
```php
$web->setConfig(['proxy' => 'http://user:password@127.0.0.1:3128']);
```
### Timeout
You can set the `timeout` using `setConfig`:
```php
$web->setConfig(['timeout' => 15]);
```
Setting the timeout to zero will disable it.
### Disabling SSL
While unrecommended, it might be required to disable SSL checks. You can do so using:
```php
$web->setConfig(['disable_ssl' => true]);
```
You can call `setConfig` multiple times. It stores the config and merges it with previous settings. This should be kept in mind in the unlikely use-case when unsetting values.
:rocket: Installation with Composer
-----------------------------------
```bash
composer require spekulatius/phpscraper
```
After the installation, the package will be picked up by the Composer autoloader. If you are using a common PHP application or framework such as Laravel or Symfony you can start scraping now :rocket:
If not or you are building a standalone-scraper, please include the autoloader in `vendor/` at the top of your file:
```php
<?php
require __DIR__ . '/vendor/autoload.php';
// ...
```
Now you can now use any of the examples on the documentation website or from the [`tests/`-folder](https://github.com/spekulatius/PHPScraper/tree/master/tests).
Please consider supporting PHPScraper with a star or [sponsorship](https://github.com/sponsors/spekulatius):
```bash
composer thanks
```
Thank you :muscle:
:white_check_mark: Testing
--------------------------
The library comes with a PHPUnit test suite. To run the tests, run the following command from the project folder:
```bash
composer test
```
You can find the tests [here](https://github.com/spekulatius/PHPScraper/tree/master/tests). The test pages are [publicly available](https://github.com/spekulatius/phpscraper-test-pages).
## MISC: [Issues](https://github.com/spekulatius/PHPScraper/issues), [Ideas](https://github.com/spekulatius/PHPScraper/milestones), [Contributing](https://github.com/spekulatius/PHPScraper/blob/master/CONTRIBUTING.md), [CHANGELOG](https://github.com/spekulatius/PHPScraper/blob/master/CHANGELOG.md), [UPGRADING](https://github.com/spekulatius/PHPScraper/blob/master/UPGRADING.md), [LICENSE](https://github.com/spekulatius/PHPScraper/blob/master/LICENSE.md)

25
lib/sc/UPGRADING.md Normal file
View file

@ -0,0 +1,25 @@
# Upgrading PHPScraper
This document will help you upgrading PHPScraper from an earlier version to later versions.
## From `0.x` to `1.x`
- The namespace has been adjusted from `\spekulatius` to `\Spekulatius\PHPScraper`. Any `use` statements or other class references need to updated accordingly:
```diff
-use spekulatius\phpscraper;
+use Spekulatius\PHPScraper\PHPScraper;
```
or
```diff
-$web = new \spekulatius\phpscraper;
+$web = new \Spekulatius\PHPScraper\PHPScraper;
```
## From `1.x` to `2.x`
- Support for PHP 7.x was dropped. PHP 8.0 is the minimum for v2.
- The publicly accessible function `parseXML` was renamed to `parseXml`.
- The codebase has been analysed with PHPStan and hardened manually. Due to this, some return types have changed. See [v2 pull request](https://github.com/spekulatius/PHPScraper/pull/187/files) for details.

81
lib/sc/composer.json Normal file
View file

@ -0,0 +1,81 @@
{
"name": "spekulatius/phpscraper",
"description": "PHPScraper, built with simplicity in mind. See tests/ for more examples.",
"keywords": [
"PHP scraper",
"PHP scraping",
"PHP crawler",
"xpath scraper",
"web scraping",
"PHP library",
"web-access"
],
"homepage": "https://phpscraper.de",
"type": "library",
"license": "GPL-3.0-or-later",
"authors": [
{
"name": "Peter Thaleikis",
"homepage": "https://peterthaleikis.com"
}
],
"require": {
"php": "^8.1",
"ext-intl": "*",
"symfony/dom-crawler": "^5.4 || ^6.0",
"donatello-za/rake-php-plus": "^1.0.15",
"league/uri": "^7.0",
"symfony/browser-kit": "^6.0",
"symfony/http-client": "^6.0",
"symfony/css-selector": "^6.0"
},
"require-dev": {
"symfony/thanks": "^1.0.0",
"phpunit/phpunit": "^8.0.0|^9.0.0",
"illuminate/collections": "^8.0.0|^9.0.0",
"laravel/pint": "^1.0",
"phpstan/phpstan": "^1.0",
"rector/rector": "^0.18",
"symfony/var-dumper": "^6.0"
},
"autoload": {
"psr-4": {
"Spekulatius\\PHPScraper\\": "src/"
}
},
"autoload-dev": {
"psr-4": {
"Spekulatius\\PHPScraper\\Tests\\": "tests/"
}
},
"scripts": {
"refactor": "./vendor/bin/rector",
"lint": "./vendor/bin/pint",
"test:refactor": "./vendor/bin/rector --dry-run",
"test:lint": "./vendor/bin/pint --test",
"test:types": "./vendor/bin/phpstan analyse --ansi src/ tests/ --level=9",
"test:unit": "./vendor/phpunit/phpunit/phpunit --cache-result --cache-result-file=.tmp/phpunit --order-by=defects --colors=always --stop-on-failure",
"test": [
"@test:refactor",
"@test:lint",
"@test:types",
"@test:unit"
]
},
"funding": [
{
"type": "github",
"url": "https://github.com/sponsors/spekulatius"
},
{
"type": "homepage",
"url": "https://phpscraper.de/misc/sponsors.html"
}
],
"config": {
"sort-packages": true,
"allow-plugins": {
"symfony/thanks": true
}
}
}

1241
lib/sc/phpstan-baseline.neon Normal file

File diff suppressed because it is too large Load diff

12
lib/sc/phpstan.neon Normal file
View file

@ -0,0 +1,12 @@
includes:
- phpstan-baseline.neon
parameters:
level: 9
paths:
- src/
- tests/
tmpDir: ./.tmp/phpstan/
ignoreErrors:
# TODO Add those return types.
- '#return type has no value type specified in iterable type array\.$#'

21
lib/sc/phpunit.xml.dist Normal file
View file

@ -0,0 +1,21 @@
<?xml version="1.0" encoding="UTF-8"?>
<phpunit
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
backupGlobals="false"
backupStaticAttributes="false"
colors="true"
convertErrorsToExceptions="true"
convertNoticesToExceptions="true"
convertWarningsToExceptions="true"
processIsolation="false"
stopOnFailure="false"
bootstrap="vendor/autoload.php"
xsi:noNamespaceSchemaLocation="https://schema.phpunit.de/9.3/phpunit.xsd"
>
<coverage/>
<testsuites>
<testsuite name="Tests">
<directory suffix="Test.php">./tests</directory>
</testsuite>
</testsuites>
</phpunit>

13
lib/sc/pint.json Normal file
View file

@ -0,0 +1,13 @@
{
"preset": "laravel",
"rules": {
"simplified_null_return": true,
"braces": false,
"new_with_braces": {
"anonymous_class": false,
"named_class": false
},
"concat_space": false,
"ordered_traits": false
}
}

13
lib/sc/playground.php Normal file
View file

@ -0,0 +1,13 @@
<?php
require __DIR__ . '/vendor/autoload.php';
echo "\n";
echo "#########################\n";
echo "# PHPScraper Playground #\n";
echo "#########################\n";
echo "\n";
echo "# Here you can try out your code or examples from phpscraper.de\n";
echo "\n";
$web = new \Spekulatius\PHPScraper\PHPScraper;

25
lib/sc/rector.php Normal file
View file

@ -0,0 +1,25 @@
<?php
declare(strict_types=1);
use Rector\CodeQuality\Rector\Class_\InlineConstructorDefaultToPropertyRector;
use Rector\Config\RectorConfig;
use Rector\Set\ValueObject\LevelSetList;
use Rector\Set\ValueObject\SetList;
return static function (RectorConfig $rectorConfig): void {
$rectorConfig->paths([
__DIR__.'/src',
]);
$rectorConfig->rules([
InlineConstructorDefaultToPropertyRector::class,
]);
$rectorConfig->sets([
// LevelSetList::UP_TO_PHP_82,
// SetList::CODE_QUALITY,
SetList::DEAD_CODE,
SetList::TYPE_DECLARATION,
]);
};

39
lib/sc/src/Core.php Normal file
View file

@ -0,0 +1,39 @@
<?php
namespace Spekulatius\PHPScraper;
/**
* This class organizes mostly. For individual functionality check the related traits please.
*/
class Core
{
/**
* Url related helpers for information about the current location and URL processing.
*/
use UsesUrls;
/**
* This trait manages the interaction with BrowserKit (formerly Goutte).
*/
use UsesBrowserKit;
/**
* This contains the basic filter methods. Make accessing data easier.
*/
use UsesXPathFilters;
/**
* This contains various content-related selectors. meta tags, h1, etc. pp.
*/
use UsesContent;
/**
* Shared simple parsers for XML, JSON and CSV.
*/
use UsesFileParsers;
/**
* This contains the feeds-related selectors and parsers: RSS, sitemap, search index, etc.
*/
use UsesFeeds;
}

View file

@ -0,0 +1,36 @@
<?php
namespace Spekulatius\PHPScraper\DataTransferObjects;
/**
* A simplified DTO to hold feed entries with incomplete data.
*
* This isn't aimed at keeping all details but the key values.
*/
class FeedEntry
{
/**
* @todo with drop of PHP7.4 we should make these public and remove the initialization above.
* @todo with drop of PHP7.4 and 8.0 we should make this `readonly`.
*/
public function __construct(
// Support for PHP7.4
public string $title,
public string $description,
public string $link
) {
}
/**
* @param array<string, string> $data
**/
public static function fromArray(array $data): self
{
// Convert to an object and return the instance.
return new self(
$data['title'] ?? '',
$data['description'] ?? '',
$data['link']
);
}
}

148
lib/sc/src/PHPScraper.php Normal file
View file

@ -0,0 +1,148 @@
<?php
namespace Spekulatius\PHPScraper;
/**
* This class manages the Clients and connections.
*
* Most calls are passed through to the Core class.
*/
use Symfony\Component\BrowserKit\HttpBrowser;
use Symfony\Component\HttpClient\HttpClient as SymfonyHttpClient;
/**
* @phpstan-type PHPScraperConfig array{'follow_redirects'?: bool, 'follow_meta_refresh'?: bool, 'max_redirects'?: int, 'agent'?: string, 'proxy'?: string|null, 'timeout'?: int, 'disable_ssl'?: bool}
*/
class PHPScraper
{
/**
* Holds the config for the clients.
*
* @var PHPScraperConfig
*/
protected $config = [];
/**
* Holds the Core class. It handles the actual scraping.
*/
protected Core $core;
/**
* @param PHPScraperConfig $config
*/
public function __construct(array $config = [])
{
// Prepare the core. It delegates all further processing.
$this->core = new Core;
// And set the config.
$this->setConfig($config);
}
/**
* Sets the config, generates the required Clients and updates the core with the new clients.
*
* @param PHPScraperConfig $config
*/
public function setConfig(array $config = []): self
{
// Define the default values
$defaults = [
// We assume that we want to follow any redirects, in reason.
'follow_redirects' => true,
'follow_meta_refresh' => true,
'max_redirects' => 5,
/**
* Agent can be overwritten using:
*
* ```php
* $web->setConfig(['agent' => 'My Agent']);
* ```
*/
'agent' => 'Mozilla/5.0 (compatible; PHP Scraper/1.x; +https://phpscraper.de)',
/**
* Setting the Proxy
*
* ```php
* $web->setConfig(['proxy' => 'http://user:password@127.0.0.1:3128']);
* ```
*/
'proxy' => null,
/**
* Timeout in seconds.
*
* ```php
* $web->setConfig(['timeout' => 15]);
* ```
*/
'timeout' => 10,
/**
* Disable SSL (not recommended unless really needed).
*
* @var bool
*/
'disable_ssl' => false,
];
// Add the defaults in
$this->config = array_merge($defaults, $config);
// Symfony HttpClient
$httpClient = SymfonyHttpClient::create([
'proxy' => $this->config['proxy'],
'timeout' => $this->config['timeout'],
'verify_host' => ! $this->config['disable_ssl'],
'verify_peer' => ! $this->config['disable_ssl'],
]);
// BrowserKit Client and set some config needed for it.
$client = new HttpBrowser($httpClient);
$client->followRedirects($this->config['follow_redirects']);
$client->followMetaRefresh($this->config['follow_meta_refresh']);
$client->setMaxRedirects($this->config['max_redirects']);
$client->setServerParameter('HTTP_USER_AGENT', $this->config['agent']);
// Set the client on the core.
$this->core->setClient($client);
$this->core->setHttpClient($httpClient);
return $this;
}
/**
* Catch calls to properties and process them accordingly.
*
* @return mixed
*/
public function __get(string $name)
{
// We are assuming that all calls for properties actually method calls...
return $this->__call($name);
}
/**
* Catches the method calls and tries to satisfy them.
*
* @param array<mixed> $arguments
* @return mixed
*/
public function __call(string $name, array $arguments = [])
{
$result = $this->core->$name(...$arguments);
// Did we get a Core class element? Keep this.
if ($result instanceof Core) {
$this->core = $result;
return $this;
}
// Otherwise: just return whatever the core returned.
return $result;
}
}

View file

@ -0,0 +1,125 @@
<?php
namespace Spekulatius\PHPScraper;
use Symfony\Component\BrowserKit\HttpBrowser;
use Symfony\Component\DomCrawler\Crawler;
use Symfony\Contracts\HttpClient\HttpClientInterface;
trait UsesBrowserKit
{
/**
* Holds the client
*
* @var \Symfony\Component\BrowserKit\HttpBrowser
*/
protected $client;
/**
* Holds the HttpClient
*
* @var \Symfony\Contracts\HttpClient\HttpClientInterface;
*/
protected $httpClient;
/**
* Holds the current page (a Crawler object)
*
* @var \Symfony\Component\DomCrawler\Crawler
*/
protected $currentPage;
/**
* Overwrites the client
*/
public function setClient(HttpBrowser $client): self
{
$this->client = $client;
return $this;
}
/**
* Overwrites the httpClient
*/
public function setHttpClient(HttpClientInterface $httpClient): self
{
$this->httpClient = $httpClient;
return $this;
}
/**
* Retrieve the client
*
* @return \Symfony\Component\BrowserKit\HttpBrowser $client
*/
public function client(): HttpBrowser
{
return $this->client;
}
/**
* Any URL-related methods are in `UsesUrls.php`.
**/
/**
* Navigates to a new page using an URL.
*/
public function go(string $url): self
{
// Keep it around for internal processing.
$this->currentPage = $this->client->request('GET', $url);
return $this;
}
/**
* Allows to set HTML content to process.
*
* This is intended to be used as a work-around, if you already have the DOM.
*/
public function setContent(string $url, string $content): self
{
// Overwrite the current page with a fresh Crawler instance of the content.
$this->currentPage = new Crawler($content, $url);
return $this;
}
/**
* Fetch an asset from a given absolute or relative URL
*/
public function fetchAsset(string $url): string
{
return $this
->httpClient
->request(
'GET',
($this->currentPage === null) ? $url : (string) $this->makeUrlAbsolute($url),
)
->getContent();
}
/**
* Click a link (either with title or url)
*
* @param string $titleOrUrl
*/
public function clickLink($titleOrUrl): self
{
// If the string starts with http just go to it - we assume it's an URL
if (\stripos($titleOrUrl, 'http') === 0) {
// Go to a URL
$this->go($titleOrUrl);
} else {
// Find link based on the title
$link = $this->currentPage->selectLink($titleOrUrl)->link();
// Click the link and store the DOMCrawler object
$this->currentPage = $this->client->click($link);
}
return $this;
}
}

563
lib/sc/src/UsesContent.php Normal file
View file

@ -0,0 +1,563 @@
<?php
namespace Spekulatius\PHPScraper;
use DonatelloZa\RakePlus\RakePlus;
use League\Uri\Uri;
use Symfony\Component\DomCrawler\Image as DomCrawlerImage;
use Symfony\Component\DomCrawler\Link as DomCrawlerLink;
trait UsesContent
{
/**
* Access conveniences: Methods to make the data more accessible.
*
* I like to have direct access to stuff without too many chained calls.
* So I've added a number of things which might be of interest.
*
* Any suggestions what is missing? Send a PR :)
*
* @see https://phpscraper.de/contributing
*/
public function title(): ?string
{
return $this->filterFirstText('//title');
}
public function charset(): ?string
{
return $this->filterFirstExtractAttribute('//meta[@charset]', ['charset']);
}
public function contentType(): ?string
{
return $this->filterFirstExtractAttribute('//meta[@http-equiv="Content-type"]', ['content']);
}
public function canonical(): ?string
{
return $this->filterFirstExtractAttribute('//link[@rel="canonical"]', ['href']);
}
public function viewportString(): ?string
{
return $this->filterFirstContent('//meta[@name="viewport"]');
}
public function viewport(): array
{
return is_null($this->viewportString()) ? [] : (array) \preg_split('/,\s*/', $this->viewportString());
}
public function csrfToken(): ?string
{
return $this->filterFirstExtractAttribute('//meta[@name="csrf-token"]', ['content']);
}
public function baseHref(): ?string
{
return $this->filterFirstExtractAttribute('//base', ['href']);
}
/**
* Get the header collected as an array
*
* @return array{charset: mixed, contentType: mixed, viewport: mixed, canonical: mixed, csrfToken: mixed}
*/
public function headers(): array
{
return [
'charset' => $this->charset(),
'contentType' => $this->contentType(),
'viewport' => $this->viewport(),
'canonical' => $this->canonical(),
'csrfToken' => $this->csrfToken(),
];
}
public function author(): ?string
{
return $this->filterFirstContent('//meta[@name="author"]');
}
public function image(): ?string
{
return $this->makeUrlAbsolute($this->filterFirstContent('//meta[@name="image"]'));
}
public function keywordString(): ?string
{
return $this->filterFirstContent('//meta[@name="keywords"]');
}
public function keywords(): array
{
return is_null($this->keywordString()) ? [] : (array) \preg_split('/,\s*/', $this->keywordString());
}
public function description(): ?string
{
return $this->filterFirstContent('//meta[@name="description"]');
}
/**
* Get the meta collected as an array
*
* @return array{author: mixed, image: mixed, keywords: mixed, description: mixed}
*/
public function metaTags(): array
{
return [
'author' => $this->author(),
'image' => $this->image(),
'keywords' => $this->keywords(),
'description' => $this->description(),
];
}
/**
* Gets all Twitter-Card attributes (`twitter:`) as an array
*
* @return array<string, string>
*/
public function twitterCard(): array
{
$data = $this
->filter('//meta[contains(@name, "twitter:")]')
->extract(['name', 'content']);
// Prepare the data
$result = [];
foreach ($data as $set) {
$result[(string) $set[0]] = (string) $set[1];
}
return $result;
}
/**
* Gets any OpenGraph attributes (`og:`) as an array
*
* @return array<string, string>
*/
public function openGraph(): array
{
$data = $this
->filter('//meta[contains(@property, "og:")]')
->extract(['property', 'content']);
// Prepare the data
$result = [];
foreach ($data as $set) {
$result[(string) $set[0]] = (string) $set[1];
}
return $result;
}
public function h1(): array
{
return $this->filterExtractAttributes('//h1', ['_text']);
}
public function h2(): array
{
return $this->filterExtractAttributes('//h2', ['_text']);
}
public function h3(): array
{
return $this->filterExtractAttributes('//h3', ['_text']);
}
public function h4(): array
{
return $this->filterExtractAttributes('//h4', ['_text']);
}
public function h5(): array
{
return $this->filterExtractAttributes('//h5', ['_text']);
}
public function h6(): array
{
return $this->filterExtractAttributes('//h6', ['_text']);
}
/**
* Get all heading tags
*
* @return array<array>
*/
public function headings(): array
{
return [
$this->h1(),
$this->h2(),
$this->h3(),
$this->h4(),
$this->h5(),
$this->h6(),
];
}
public function lists(): array
{
$lists = [];
/** @var \DOMElement $list */
foreach ($this->currentPage->filter('ol, ul') as $list) {
$lists[] = [
'type' => $list->tagName,
'children' => $list->childNodes,
'children_plain' => array_values(array_filter(array_map('trim', explode("\n", $list->textContent)))),
];
}
return $lists;
}
/**
* @return array<string>
**/
public function orderedLists(): array
{
return array_values(array_filter($this->lists(), fn ($list): bool => $list['type'] === 'ol'));
}
/**
* @return array<string>
**/
public function unorderedLists(): array
{
return array_values(array_filter($this->lists(), fn ($list): bool => $list['type'] === 'ul'));
}
/**
* @return array<string>
**/
public function paragraphs(): array
{
return array_map(
'trim',
$this->filterExtractAttributes('//p', ['_text'])
);
}
/**
* Get the paragraphs of the page excluding empty paragraphs.
*/
public function cleanParagraphs(): array
{
return array_values(array_filter(
$this->paragraphs(),
fn ($paragraph): bool => $paragraph !== ''
));
}
/**
* Parses the content outline of the web-page
*
* @return array<string>
*/
public function outline(): array
{
$result = $this->filterExtractAttributes('//h1|//h2|//h3|//h4|//h5|//h6', ['_name', '_text']);
foreach ($result as $index => $array) {
$result[$index] = array_combine(['tag', 'content'], (array) $array);
}
return $result;
}
/**
* Parses the content outline of the web-page
*
* @return array<array>
*/
public function outlineWithParagraphs(): array
{
$result = $this->filterExtractAttributes('//h1|//h2|//h3|//h4|//h5|//h6|//p', ['_name', '_text']);
foreach ($result as $index => $array) {
$result[$index] = array_combine(['tag', 'content'], (array) $array);
$result[$index]['content'] = trim((string) $result[$index]['content']);
}
return $result;
}
/**
* Parses the content outline of the web-page
*/
public function cleanOutlineWithParagraphs(): array
{
$elementsNameAndText = $this->filterExtractAttributes('//h1|//h2|//h3|//h4|//h5|//h6|//p', ['_name', '_text']);
/** @var array<string> $nameAndText */
foreach ($elementsNameAndText as $index => $nameAndText) {
// Element has no text.
if ($nameAndText[1] === '') {
continue;
}
$elementsNameAndText[$index] = [
'tag' => $nameAndText[0],
'content' => trim($nameAndText[1]),
];
}
return $elementsNameAndText;
}
/**
* Internal method to prepare the content for keyword analysis
* done in the called methods for the rake analysis
*
* Uses:
*
* - Title
* - Headings
* - Paragraphs/Content
* - Link anchors and Titles
* - Alt Texts of Images
* - Meta Title, Description and Keywords
*
* @see https://github.com/Donatello-za/rake-php-plus
* @see https://phpscraper.de/examples/extract-keywords.html
* @see https://github.com/spekulatius/phpscraper-keyword-scraping-example
*
* @return array<string>
*/
protected function prepContent(): array
{
// Collect content strings
$content = array_merge(
// Website title
[$this->title()],
// Paragraphs
$this->paragraphs(),
// Various meta tags
[
$this->author(),
$this->description(),
implode(' ', $this->keywords()),
]
);
// Add headings
foreach ($this->headings() as $headings) {
$content += array_values($headings);
}
// Add image alt texts in
foreach ($this->linksWithDetails() as $link) {
$content[] = $link['text'];
$content[] = $link['title'];
}
foreach ($this->imagesWithDetails() as $image) {
$content[] = $image['alt'];
}
return $content;
}
/**
* Gets a set of keywords based on the rake approach.
*
* Uses:
*
* - Title
* - Headings
* - Paragraphs/Content
* - Link anchors and Titles
* - Alt Texts of Images
* - Meta Title, Description and Keywords
*
* @see https://github.com/Donatello-za/rake-php-plus
* @see https://phpscraper.de/examples/extract-keywords.html
* @see https://github.com/spekulatius/phpscraper-keyword-scraping-example
*
* @param string $locale (default: 'en_US')
*/
public function contentKeywords($locale = 'en_US'): array
{
// Extract the keyword phrases and return a sorted array
return RakePlus::create(implode(' ', $this->prepContent()), $locale)
->sort('asc')
->get();
}
/**
* Gets a set of keywords with scores based on the rake approach
*
* Uses:
*
* - Title
* - Headings
* - Paragraphs/Content
* - Link anchors and Titles
* - Alt Texts of Images
* - Meta Title, Description and Keywords
*
* @see https://github.com/Donatello-za/rake-php-plus
* @see https://phpscraper.de/examples/extract-keywords.html
* @see https://github.com/spekulatius/phpscraper-keyword-scraping-example
*
* @param string $locale (default: 'en_US')
*/
public function contentKeywordsWithScores($locale = 'en_US'): array
{
// Extract the keyword phrases and return a sorted array
return RakePlus::create(implode(' ', $this->prepContent()), $locale)
->sortByScore('desc')
->scores();
}
/**
* Get all links on the page as absolute URLs
*
* @see https://github.com/spekulatius/link-scraping-test-beautifulsoup-vs-phpscraper
*/
public function links(): array
{
$links = $this->filter('//a')->links();
// Generate a list of all image entries
$result = [];
foreach ($links as $link) {
$result[] = $link->getUri();
}
return $result;
}
/**
* Get all internal links (same root or sub-domain) on the page as absolute URLs
*/
public function internalLinks(): array
{
// Get the current host - to compare against for internal links
$currentRootDomain = $this->currentHost();
// Filter the array
return array_values(array_filter(
$this->links(),
function ($link) use (&$currentRootDomain): bool {
$linkRootDomain = Uri::new($link)->getHost();
return $currentRootDomain === $linkRootDomain;
}
));
}
/**
* Get all external links on the page as absolute URLs
*/
public function externalLinks(): array
{
// Diff the array
return array_values(array_diff(
$this->links(),
$this->internalLinks()
));
}
/**
* Get all links on the page with commonly interesting details
*/
public function linksWithDetails(): array
{
/** @var array<\DOMElement> $links */
$links = $this->filter('//a');
// Generate a list of all image entries
$result = [];
foreach ($links as $link) {
// Check if the anchor is only an image. If so, wrap it into DomCrawler\Image to get the Uri.
$image = [];
/** @var \DOMElement $childNode */
foreach ($link->childNodes as $childNode) {
if ($childNode->nodeName === 'img') {
$image[] = (new DomCrawlerImage($childNode, $this->currentBaseHost()))->getUri();
}
}
// Collect commonly interesting attributes and URL
$rel = $link->getAttribute('rel');
// Generate the proper uri using the Symfony's link class
$uri = (new DomCrawlerLink($link, $this->currentBaseHost()))->getUri();
// Prepare the result set.
$entry = [
'url' => $uri,
'protocol' => str_contains($uri, ':') ? explode(':', $uri)[0] : null,
'text' => trim($link->nodeValue ?? ''),
'title' => $link->getAttribute('title') === '' ? null : $link->getAttribute('title'),
'target' => $link->getAttribute('target') === '' ? null : $link->getAttribute('target'),
'rel' => ($rel === '') ? null : strtolower($rel),
'image' => $image,
'isNofollow' => ($rel === '') ? false : str_contains($rel, 'nofollow'),
'isUGC' => ($rel === '') ? false : str_contains($rel, 'ugc'),
'isSponsored' => ($rel === '') ? false : str_contains($rel, 'sponsored'),
'isMe' => ($rel === '') ? false : str_contains($rel, 'me'),
'isNoopener' => ($rel === '') ? false : str_contains($rel, 'noopener'),
'isNoreferrer' => ($rel === '') ? false : str_contains($rel, 'noreferrer'),
];
$result[] = $entry;
}
return $result;
}
/**
* Get all images on the page with absolute URLs
*/
public function images(): array
{
// Generate a list of all image entries
$result = [];
$images = $this->filter('//img')->images();
/** @var \Symfony\Component\DomCrawler\Image $image */
foreach ($images as $image) {
$result[] = $image->getUri();
}
return $result;
}
/**
* Get all images on the page with commonly interesting details
*/
public function imagesWithDetails(): array
{
// Generate a list of all image entries
$result = [];
/** @var array<\DOMElement> $images */
$images = $this->filter('//img');
foreach ($images as $image) {
// Collect the URL and commonly interesting attributes
$result[] = [
// Re-generate the proper uri using the Symfony's image class
'url' => (new DomCrawlerImage($image, $this->currentBaseHost()))->getUri(),
'alt' => $image->getAttribute('alt'),
'width' => $image->getAttribute('width') === '' ? null : $image->getAttribute('width'),
'height' => $image->getAttribute('height') === '' ? null : $image->getAttribute('height'),
];
}
return $result;
}
}

130
lib/sc/src/UsesFeeds.php Normal file
View file

@ -0,0 +1,130 @@
<?php
namespace Spekulatius\PHPScraper;
use Spekulatius\PHPScraper\DataTransferObjects\FeedEntry;
trait UsesFeeds
{
/**
* Returns a guessed sitemap URL based on the current host. Usually it's `/sitemap.xml`.
*/
public function sitemapUrl(): string
{
return $this->currentBaseHost() . '/sitemap.xml';
}
/**
* Resolves the sitemap and returns an array with raw data.
*
* @return array $sitemap
*/
public function sitemapRaw(string $url = null): array
{
return $this->parseXml($this->fetchAsset($url ?? $this->sitemapUrl()));
}
/**
* Resolves the sitemap and returns an array of `FeedEntry`-DTOs.
*
* @todo Support for text-only sitemaps, split versions, image-sitemaps, etc.?
*
* @return array<FeedEntry> $sitemap
*/
public function sitemap(string $url = null): array
{
return array_map(
// Create the generic DTO for each
fn ($entry): FeedEntry => FeedEntry::fromArray([
'title' => '',
'description' => '',
'link' => $entry['loc'],
]),
// Fetch the sitemap URL, parse it and select the `url` section.
$this->sitemapRaw($url)['url']
);
}
/**
* Returns the usual location (URL) for the static search index.
*/
public function searchIndexUrl(): string
{
return $this->currentBaseHost() . '/index.json';
}
/**
* Returns an array of the parsed search index JSON.
*
* @return array $searchIndex
*/
public function searchIndexRaw(string $url = null): array
{
return $this->parseJson($this->fetchAsset($url ?? $this->searchIndexUrl()));
}
/**
* Resolves the search index and returns an array of `\Spekulatius\PHPScraper\DataTransferObjects\FeedEntry`.
*
* @return array<FeedEntry> $searchIndex
*/
public function searchIndex(string $url = null): array
{
return array_map(
// Create the generic DTO for each
fn ($entry): FeedEntry => FeedEntry::fromArray([
'title' => $entry['title'],
'description' => $entry['snippet'],
'link' => $entry['link'],
]),
// Fetch the sitemap URL, parse it and select the `url` section.
$this->searchIndexRaw($url)
);
}
/**
* Compiles a list of RSS urls based on the <link>-tags on the current page.
*
* @return array<string>
*/
public function rssUrls(): array
{
$urls = $this->filterExtractAttributes('//link[@type="application/rss+xml"]', ['href']);
return array_map(fn ($url): string => (string) $this->makeUrlAbsolute($url), $urls);
}
/**
* Fetches a given set of RSS feeds and returns one array with raw data.
*
* @return array $rss
*/
public function rssRaw(?string ...$urls): array
{
return array_map(
fn ($url) => $this->parseXml($this->fetchAsset((string) $url)),
$urls === [] ? $this->rssUrls() : $urls
);
}
/**
* Fetches a given set of RSS feeds and returns one array with raw data.
*
* @return array<FeedEntry> $rss
*/
public function rss(?string ...$urls): array
{
return array_map(
// Create the generic DTO for each
fn ($entry): FeedEntry => FeedEntry::fromArray([
'title' => $entry['title'],
'link' => $entry['link']['@attributes']['href'],
]),
// Fetch the rss URLs, parse it and select the `url` section.
$this->rssRaw(...$urls)[0]['entry']
);
}
}

View file

@ -0,0 +1,340 @@
<?php
namespace Spekulatius\PHPScraper;
trait UsesFileParsers
{
/**
* Base Util to decode a CSV string.
*
* @return array $data
*/
public function csvDecodeRaw(
string $csvString,
string $separator = null,
string $enclosure = null,
string $escape = null
): array {
try {
$csv = array_map(
fn ($line) => str_getcsv($line, $separator ?? ',', $enclosure ?? '"', $escape ?? '\\'),
explode("\n", $csvString)
);
// While technically 'valid', a single string isn't overly useful and likely not actually a CSV but an URL.
if (count($csv) === 1 && count($csv[0]) === 1) {
throw new \Exception('Does not look CSV-like');
}
} catch (\Exception $e) {
throw new \Exception('Failed to parse CSV: ' . $e->getMessage());
}
return $csv;
}
/**
* Decode CSV and cast types.
*
* @return array $data
*/
public function csvDecode(
string $csvString,
string $separator = null,
string $enclosure = null,
string $escape = null
): array {
try {
$csv = $this->csvDecodeRaw($csvString, $separator, $enclosure, $escape);
// Cast native and custom types
$csv = array_map(
fn ($line): array => array_map(
fn ($cell) => $this->castType($cell),
$line
),
$csv
);
} catch (\Exception $e) {
throw new \Exception('Failed to parse CSV: ' . $e->getMessage());
}
return $csv;
}
/**
* Util to decode a CSV string to asso. array.
*
* @return array $data
*/
public function csvDecodeWithHeaderRaw(
string $csvString,
string $separator = null,
string $enclosure = null,
string $escape = null
): array {
try {
$csv = $this->csvDecodeRaw($csvString, $separator, $enclosure, $escape);
$header = array_shift($csv);
// Combine the rows with the header entry.
array_walk(
$csv,
function (&$row, $key, $header): void {
$row = array_combine($header, $row);
},
$header
);
} catch (\Exception $e) {
throw new \Exception('Failed to parse CSV: ' . $e->getMessage());
}
return $csv;
}
/**
* Decode a CSV string to asso. array and cast types.
*
* @return array $data
*/
public function csvDecodeWithHeader(
string $csvString,
string $separator = null,
string $enclosure = null,
string $escape = null
): array {
try {
$csv = $this->csvDecodeWithHeaderRaw($csvString, $separator, $enclosure, $escape);
// Cast native and custom types
foreach ($csv as $idx => $row) {
foreach ($row as $key => $value) {
$csv[$idx][$key] = $this->castType($value);
}
}
} catch (\Exception $e) {
throw new \Exception('Failed to parse CSV: ' . $e->getMessage());
}
return $csv;
}
/**
* Helper method to cast types
*/
public function castType(string $entry): int|float|string
{
// Looks like an int?
if ($entry == (int) $entry) {
return (int) $entry;
}
// Looks like a float?
if ($entry == (float) $entry) {
return (float) $entry;
}
return $entry;
}
/**
* Parses a given CSV string or fetches the URL and parses it.
*
* @return array $data
*/
public function parseCsv(
string $csvStringOrUrl = null,
string $separator = null,
string $enclosure = null,
string $escape = null
): array {
// Check if we got either a current page or at least a URL string to process
if ($csvStringOrUrl === null && $this->currentPage === null) {
throw new \Exception('You can not call parseCsv() without parameter or initial navigation.');
}
try {
// If we have a string, let's try to parse the CSV from this.
if ($csvStringOrUrl !== null) {
// Simple: Try to parse what we have been given
try {
$result = $this->csvDecode($csvStringOrUrl, $separator, $enclosure, $escape);
} catch (\Exception $e) {
// We don't do anything if it fails - likely we have an URL. Let's continue below.
}
}
/**
* We fetch the content and process it, if we haven't got a CSV as a string.
*
* This is a work-around to allow for:
*
* - `$web->parseCsv('https://...')`.
* - `$web->go('...')->parseCsv()`.
*/
$result = $result ?? $this->csvDecode(
// Fetch the resource either using $csvStringOrUrl
$this->fetchAsset(
// Fallback on the current URL, if needed and possible (`go` was used before).
$csvStringOrUrl ?? $this->currentUrl()
),
$separator,
$enclosure,
$escape
);
} catch (\Exception $e) {
throw new \Exception('Failed to parse CSV: ' . $e->getMessage());
}
return (array) $result;
}
/**
* Parses a given CSV string into an asso. with headers or fetches the URL and parses it.
*
* @return array $data
*/
public function parseCsvWithHeader(
string $csvStringOrUrl = null,
string $separator = null,
string $enclosure = null,
string $escape = null
): array {
// Check if we got either a current page or at least a URL string to process
if ($csvStringOrUrl === null && $this->currentPage === null) {
throw new \Exception('You can not call parseCsvWithHeader() without parameter or initial navigation.');
}
try {
// If we have a string, let's try to parse the CSV from this.
if ($csvStringOrUrl !== null) {
// Simple: Try to parse what we have been given
try {
$result = $this->csvDecodeWithHeader($csvStringOrUrl, $separator, $enclosure, $escape);
} catch (\Exception $e) {
// We don't do anything if it fails - likely we have an URL. Let's continue below.
}
}
/**
* We fetch the content and process it, if we haven't got a CSV as a string.
*
* This is a work-around to allow for:
*
* - `$web->parseCsvWithHeader('https://...')`.
* - `$web->go('...')->parseCsvWithHeader()`.
*/
$result = $result ?? $this->csvDecodeWithHeader(
// Fetch the resource either using $csvStringOrUrl
$this->fetchAsset(
// Fallback on the current URL, if needed and possible (`go` was used before).
$csvStringOrUrl ?? $this->currentUrl()
),
$separator,
$enclosure,
$escape
);
} catch (\Exception $e) {
throw new \Exception('Failed to parse CSV: ' . $e->getMessage());
}
return (array) $result;
}
/**
* Parses a given JSON string or fetches the URL and parses it.
*
* @return array $data
*/
public function parseJson(string $jsonStringOrUrl = null): array
{
// Check if we got either a current page or at least a URL string to process
if ($jsonStringOrUrl === null && $this->currentPage === null) {
throw new \Exception('You can not call parseJson() without parameter or initial navigation.');
}
try {
// If we have a string, let's try to parse the JSON from this.
if ($jsonStringOrUrl !== null) {
// Simple: Try to parse what we have been given
try {
$result = json_decode($jsonStringOrUrl, true, 512, JSON_THROW_ON_ERROR);
} catch (\Exception $e) {
// We don't do anything if it fails - likely we have an URL. Let's continue below.
}
}
/**
* We fetch the content and process it, if we haven't got a JSON as a string.
*
* This is a work-around to allow for:
*
* - `$web->parseJson('https://...')`.
* - `$web->go('...')->parseJson()`.
*/
$result = $result ?? json_decode(
// Fetch the resource either using $jsonStringOrUrl
$this->fetchAsset(
// Fallback on the current URL, if needed and possible (`go` was used before).
$jsonStringOrUrl ?? $this->currentUrl()
),
true,
512,
JSON_THROW_ON_ERROR
);
} catch (\Exception $e) {
throw new \Exception('Failed to parse JSON: ' . $e->getMessage());
}
return (array) $result;
}
/**
* Parses a given XML string or fetches the URL and parses it.
*
* @return array $data
*/
public function parseXml(string $xmlStringOrUrl = null): array
{
// Check if we got either a current page or at least a URL string to process
if ($xmlStringOrUrl === null && $this->currentPage === null) {
throw new \Exception('You can not call parseXml() without parameter or initial navigation.');
}
try {
// Try to parse the XML. If it works we have got an XML string.
if ($xmlStringOrUrl !== null) {
try {
$result = $this->xmlDecode($xmlStringOrUrl);
} catch (\Exception $e) {
// Do nothing, we just want to try it if it works.
}
}
/**
* We fetch the content and process it, if we haven't got a XML as a string.
*
* This is a work-around to allow for:
*
* - `$web->parseXml('https://...')`.
* - `$web->go('...')->parseXml()`.
*/
$result = $result ?? $this->xmlDecode($this->fetchAsset(
$xmlStringOrUrl ?? $this->currentUrl()
));
} catch (\Exception $e) {
throw new \Exception('Failed to parse XML: ' . $e->getMessage());
}
return $result;
}
protected function xmlDecode(string $xmlString): array
{
// XML parser
$xml = simplexml_load_string(trim($xmlString), 'SimpleXMLElement', LIBXML_NOCDATA);
// Convert XML to JSON and then to an associative array
return (array) json_decode(json_encode($xml, JSON_THROW_ON_ERROR), true, 512, JSON_THROW_ON_ERROR);
}
}

68
lib/sc/src/UsesUrls.php Normal file
View file

@ -0,0 +1,68 @@
<?php
namespace Spekulatius\PHPScraper;
use League\Uri\Http;
use League\Uri\Uri;
use League\Uri\UriResolver;
trait UsesUrls
{
/**
* Returns the current url - this is either set by `go` indirectly or directly using `setContent`.
*
* @return string $url
*
* @throws \Exception
*/
public function currentUrl(): string
{
// Ensure we aren't having a "call on null" without context.
if ($this->currentPage === null) {
throw new \Exception('You can not access the URL before your first navigation using `go`.');
}
return (string) $this->currentPage->getUri();
}
/**
* Returns the current host
*
* @return string|null $host
*/
public function currentHost(): ?string
{
return Uri::new($this->currentUrl())->getHost();
}
/**
* Returns the current host as defined in `<base href="...">` or the current host.
*
* @return string $baseUrl
*/
public function currentBaseHost(): string
{
$uri = Uri::new($this->baseHref() ?? $this->currentUrl());
return $uri->getScheme() . '://' . $uri->getHost();
}
/**
* Converts a current URL to be absolute based on <base> or current page.
*
* @return ?string $absoluteUrl
*/
public function makeUrlAbsolute(string $url = null, string $baseUrl = null): ?string
{
// Allow to pass null through
if ($url === null || $this->currentPage === null) {
return null;
}
// Resolve the Url using one of the provided/set base href.
return (string) UriResolver::resolve(
Http::new($url),
Http::new($baseUrl ?? $this->baseHref() ?? $this->currentBaseHost()),
);
}
}

View file

@ -0,0 +1,79 @@
<?php
namespace Spekulatius\PHPScraper;
use Symfony\Component\DomCrawler\Crawler;
trait UsesXPathFilters
{
/**
* Filters the current page by a xPath-query
*/
public function filter(string $query): Crawler
{
return $this->currentPage->filterXPath($query);
}
/**
* Filters the current page by a xPath-query and returns the first one, or null.
*/
public function filterFirst(string $query): ?Crawler
{
$filteredNodes = $this->filter($query);
return ($filteredNodes->count() === 0) ? null : $filteredNodes->first();
}
/**
* Filters the current page by a xPath-query and returns the first ones content, or null.
*/
public function filterFirstText(string $query): ?string
{
$filteredNodes = $this->filter($query);
return ($filteredNodes->count() === 0) ? null : $filteredNodes->first()->text();
}
/**
* Filters the current page by a xPath-query and returns the textual content as array.
*
* @return array<string>
*/
public function filterTexts(string $query): array
{
return $this->filterExtractAttributes($query, ['_text']);
}
/**
* Filters the current page by a xPath-query and returns the selected attributes as array.
*
* @param array<string> $attributes
* @return array<string>
*/
public function filterExtractAttributes(string $query, array $attributes): array
{
$filteredNodes = $this->filter($query);
return ($filteredNodes->count() === 0) ? [] : $filteredNodes->extract($attributes);
}
/**
* Filters the current page by a xPath-query and returns the selected attributes of the first match.
*
* @param array<string> $attributes
*/
public function filterFirstExtractAttribute(string $query, array $attributes): ?string
{
$filteredNodes = $this->filter($query);
return ($filteredNodes->count() === 0) ? null : $filteredNodes->first()->extract($attributes)[0];
}
/**
* Returns the content attribute for the first result of the query, or null.
*/
public function filterFirstContent(string $query): ?string
{
return $this->filterFirstExtractAttribute($query, ['content']);
}
}

View file

@ -0,0 +1,43 @@
<?php
namespace Spekulatius\PHPScraper\Tests;
/**
* This tests only the `<base href="...">`-extraction.
*
* If you are looking for any URL-related tests check `UrlTest.php`.
*/
class BaseHrefTest extends \PHPUnit\Framework\TestCase
{
/**
* @test
*/
public function testMissingBaseHref()
{
$web = new \Spekulatius\PHPScraper\PHPScraper;
// Navigate to the test page.
$web->go('https://test-pages.phpscraper.de/meta/missing.html');
// Check the baseHref as not given (null)
$this->assertNull($web->baseHref);
}
/**
* @test
*/
public function testBaseHref()
{
$web = new \Spekulatius\PHPScraper\PHPScraper;
// Navigate to the test page.
// Contains: <base href="https://test-pages-with-base-href.phpscraper.de/">
$web->go('https://test-pages.phpscraper.de/meta/image/absolute-path-with-base-href.html');
// Check the baseHref
$this->assertSame(
'https://test-pages-with-base-href.phpscraper.de/',
$web->baseHref
);
}
}

View file

@ -0,0 +1,38 @@
<?php
namespace Spekulatius\PHPScraper\Tests;
class CanonicalTest extends \PHPUnit\Framework\TestCase
{
/**
* @test
*/
public function testMissingCanonical()
{
$web = new \Spekulatius\PHPScraper\PHPScraper;
// Go to the test page
$web->go('https://test-pages.phpscraper.de/meta/missing.html');
// null if there isn't a canonical set.
$this->assertNull($web->canonical);
}
/**
* @test
*/
public function testWithCanonical()
{
$web = new \Spekulatius\PHPScraper\PHPScraper;
// Navigate to the test page.
// It contains: <link rel="canonical" href="https://test-pages.phpscraper.de/navigation/2.html" />
$web->go('https://test-pages.phpscraper.de/navigation/1.html');
// Check the canonical
$this->assertSame(
'https://test-pages.phpscraper.de/navigation/2.html',
$web->canonical
);
}
}

93
lib/sc/tests/CoreTest.php Normal file
View file

@ -0,0 +1,93 @@
<?php
namespace Spekulatius\PHPScraper\Tests;
class CoreTest extends \PHPUnit\Framework\TestCase
{
/**
* @test
*/
public function testMethodAndPropertyCallsAreEqual()
{
$web = new \Spekulatius\PHPScraper\PHPScraper;
// Navigate to test page
$web->go('https://phpscraper.de');
// Both the method call as well as property call should return the same...
$this->assertSame($web->title, $web->title());
}
/**
* Test if our local variable is updated correctly.
*
* @test
*/
public function testChangeOfCurrentPage()
{
$web = new \Spekulatius\PHPScraper\PHPScraper;
// 1. Navigate to test page
$web->go('https://test-pages.phpscraper.de/meta/lorem-ipsum.html');
// Both the method call as well as property call should return the same...
$this->assertSame(
'https://test-pages.phpscraper.de/meta/lorem-ipsum.html',
$web->currentUrl
);
$this->assertSame(
'Lorem Ipsum',
$web->title
);
// 2. Leave the current page and head on to the next one.
$web->go('https://phpscraper.de');
// We should have navigated.
$this->assertSame(
'https://phpscraper.de',
$web->currentUrl
);
// Shouldn't match, because we surfed on...
$this->assertNotSame(
'https://test-pages.phpscraper.de/meta/lorem-ipsum.html',
$web->currentUrl
);
$this->assertNotSame(
'Lorem Ipsum',
$web->title
);
}
/**
* Calls should be chainable and easy to access.
*
* @test
*/
public function testBasicChainability()
{
// Testing env: First h1: "We are testing here & elsewhere!"
$url = 'https://test-pages.phpscraper.de/meta/html-entities.html';
// Test 1: Create, navigate to the test page.
$web = new \Spekulatius\PHPScraper\PHPScraper;
$web->go($url);
// Check the h1
$this->assertSame(
'We are testing here & elsewhere!',
$web->h1[0]
);
// Test 2: Chained
$this->assertSame(
'We are testing here & elsewhere!',
// Chained
(new \Spekulatius\PHPScraper\PHPScraper)
->go($url)
->h1[0]
);
}
}

View file

@ -0,0 +1,104 @@
<?php
namespace Spekulatius\PHPScraper\Tests;
class CustomSelectorTest extends \PHPUnit\Framework\TestCase
{
/**
* @test
*/
public function testFailedSelectionBasedOnId()
{
// Navigate to test page
$web = new \Spekulatius\PHPScraper\PHPScraper;
$web->go('https://test-pages.phpscraper.de/content/selectors.html');
// Ensure we got the test page.
$this->assertSame(
'Selector Tests',
$web->title
);
// Trigger failing test.
try {
$web->filterFirstText("//[@id='by-id']");
} catch (\Exception $e) {
$this->assertSame(
'DOMXPath::query(): Invalid expression',
$e->getMessage()
);
}
}
/**
* @test
*/
public function testSelectionBasedOnId()
{
// Navigate to test page
$web = new \Spekulatius\PHPScraper\PHPScraper;
$web->go('https://test-pages.phpscraper.de/content/selectors.html');
// Ensure we got the test page.
$this->assertSame(
'Selector Tests',
$web->title
);
// Select content using `->text()`
$this->assertSame(
'Content by ID',
$web->filterFirstText("//*[@id='by-id']")
);
}
/**
* @test
*/
public function testSelectionBasedOnTag()
{
// Navigate to test page
$web = new \Spekulatius\PHPScraper\PHPScraper;
$web->go('https://test-pages.phpscraper.de/content/selectors.html');
// Ensure we got the test page.
$this->assertSame(
'Selector Tests',
$web->title
);
// Select single string using first and chain `->text()`
$this->assertSame(
'Selector Tests (h1)',
$web->filterFirst('//h1')->text()
);
// Select as array using `filterTexts`:
$this->assertSame(
['Selector Tests (h1)'],
$web->filterTexts('//h1')
);
}
/**
* @test
*/
public function testSelectionBasedOnClass()
{
// Navigate to test page
$web = new \Spekulatius\PHPScraper\PHPScraper;
$web->go('https://test-pages.phpscraper.de/content/selectors.html');
// Ensure we got the test page.
$this->assertSame(
'Selector Tests',
$web->title
);
// Select without `->text()` and using the filterTexts-method instead.
$this->assertSame(
['Content by Class 1', 'Content by Class 2'],
$web->filterTexts("//*[@class='by-class']")
);
}
}

View file

@ -0,0 +1,71 @@
<?php
namespace Spekulatius\PHPScraper\Tests;
class DownloadTest extends \PHPUnit\Framework\TestCase
{
/**
* @test
*/
public function testMissingDownload()
{
$web = new \Spekulatius\PHPScraper\PHPScraper;
$this->expectException(\Symfony\Component\HttpClient\Exception\ClientException::class);
$this->expectExceptionMessage('HTTP/2 404 returned for "https://phpscraper.de/broken-url"');
$web->fetchAsset('https://phpscraper.de/broken-url');
}
/**
* @test
*/
public function testDownload()
{
// Downloads the PHPScraper sitemap and ensures the homepage is included (valid download and output).
$web = new \Spekulatius\PHPScraper\PHPScraper;
$xmlString = $web->fetchAsset('https://phpscraper.de/sitemap.xml');
// Convert XML to array
// Credit: https://stackoverflow.com/a/20431742
$xml = simplexml_load_string($xmlString, 'SimpleXMLElement', LIBXML_NOCDATA);
$array = json_decode((string) json_encode($xml), true);
$urls = array_map(
fn ($url) => $url['loc'],
$array['url']
);
$this->assertContains(
'https://phpscraper.de/',
$urls
);
}
/**
* We should support both absolute and relative URLs.
*
* Here we use the sitemap test page as a reference.
*
* @test
*/
public function testDifferentUrlTypes()
{
$web = new \Spekulatius\PHPScraper\PHPScraper;
// Navigate to the test page. As the URL is predefined, it's only about the base URL.
$web->go('https://test-pages.phpscraper.de/meta/feeds.html');
// Test 1: Absolute URL
$this->assertSame(
$web->fetchAsset($web->sitemapUrl),
$web->fetchAsset($web->currentBaseHost . '/custom_sitemap.xml'),
);
// Test 2: Relative URL
$this->assertSame(
$web->fetchAsset($web->sitemapUrl),
$web->fetchAsset('/custom_sitemap.xml'),
);
}
}

View file

@ -0,0 +1,172 @@
<?php
namespace Spekulatius\PHPScraper\Tests;
use Spekulatius\PHPScraper\DataTransferObjects\FeedEntry;
class FeedRssTest extends \PHPUnit\Framework\TestCase
{
/**
* @test
*/
public function testMissingRssUrls()
{
$web = new \Spekulatius\PHPScraper\PHPScraper;
// Navigate to the test page.
$web->go('https://test-pages.phpscraper.de/meta/missing.html');
// This page shouldn't contain any RSS feeds.
$this->assertEmpty($web->rssUrls);
}
/**
* @test
*/
public function testRssUrls()
{
$web = new \Spekulatius\PHPScraper\PHPScraper;
// Navigate to the test page.
$web->go('https://test-pages.phpscraper.de/meta/feeds.html');
// Did we get the expected result? Any URLs should be made absolute.
$this->assertSame([
'https://test-pages.phpscraper.de/absolute.xml',
'https://test-pages.phpscraper.de/relative.xml',
], $web->rssUrls);
}
/**
* Tests if we can use a custom url instead of a identified one.
*
* @test
*/
public function testCustomRssUrl()
{
$web = new \Spekulatius\PHPScraper\PHPScraper;
// Navigate to the test page.
$web->go('https://test-pages.phpscraper.de/meta/feeds.html');
// We should always allow to use a custom url.
// Both files are the same.
// One URL isn't linked from the feeds.html and therefore is custom.
$this->assertSame(
$web->rssRaw('https://test-pages.phpscraper.de/custom_rss.xml'),
$web->rssRaw('https://test-pages.phpscraper.de/relative.xml')
);
}
/**
* We should support both absolute and relative URLs.
*
* @test
*/
public function testDifferentRssUrlTypes()
{
$web = new \Spekulatius\PHPScraper\PHPScraper;
// Navigate to the test page. As the URL is predefined, it's only about the base URL.
$web->go('https://test-pages.phpscraper.de/meta/feeds.html');
// Test 1: Absolute URL
$this->assertSame(
$web->rssRaw($web->rssUrls[0]),
$web->rssRaw($web->currentBaseHost . '/custom_rss.xml'),
);
// Test 2: Relative URL
$this->assertSame(
$web->rssRaw($web->rssUrls[0]),
$web->rssRaw('/custom_rss.xml'),
);
}
/**
* Tests the raw parsing.
*
* @test
*/
public function testRssRawContent()
{
$web = new \Spekulatius\PHPScraper\PHPScraper;
// Navigate to the test page.
$web->go('https://test-pages.phpscraper.de/meta/feeds.html');
// The raw RSS is rather unhandy to work with. Let's put it in a var before testing stuff.
$rssRaw = $web->rssRaw('https://test-pages.phpscraper.de/custom_rss.xml')[0]['entry'];
// Ensure the structure is an nested array
$this->assertTrue(is_array($rssRaw));
$this->assertTrue(is_array($rssRaw[4]));
// Check some entries to ensure the parsing works.
$this->assertSame(
$rssRaw[4]['link']['@attributes']['href'],
'https://peterthaleikis.com/posts/how-i-built-my-first-browser-extension/'
);
$this->assertSame(
$rssRaw[2]['link']['@attributes']['href'],
'https://peterthaleikis.com/posts/how-to-use-pug-on-netlify/'
);
$this->assertSame(
$rssRaw[0]['link']['@attributes']['href'],
'https://peterthaleikis.com/posts/startup-name-check:-experiences-of-the-first-week/'
);
}
/**
* Tests the DTO creation.
*
* @test
*/
public function testRss()
{
$web = new \Spekulatius\PHPScraper\PHPScraper;
// Navigate to the test page.
$web->go('https://test-pages.phpscraper.de/meta/feeds.html');
// The raw RSS is rather unhandy to work with (hence we actually use the DTOs).
$rss = $web->rss('https://test-pages.phpscraper.de/custom_rss.xml');
// Check the count
$this->assertSame(37, count($rss));
// Check some entries to ensure the parsing works.
// Set 1
$this->assertTrue($rss[4] instanceof FeedEntry);
$this->assertSame(
$rss[4]->title,
'How I Built My First Browser Extension'
);
$this->assertSame(
$rss[4]->link,
'https://peterthaleikis.com/posts/how-i-built-my-first-browser-extension/'
);
// Set 2
$this->assertTrue($rss[2] instanceof FeedEntry);
$this->assertSame(
$rss[2]->title,
'How to Use Pug on Netlify?'
);
$this->assertSame(
$rss[2]->link,
'https://peterthaleikis.com/posts/how-to-use-pug-on-netlify/'
);
// Set 3
$this->assertTrue($rss[0] instanceof FeedEntry);
$this->assertSame(
$rss[0]->title,
'Startup Name Check: Experiences of the First week'
);
$this->assertSame(
$rss[0]->link,
'https://peterthaleikis.com/posts/startup-name-check:-experiences-of-the-first-week/'
);
}
}

View file

@ -0,0 +1,192 @@
<?php
namespace Spekulatius\PHPScraper\Tests;
use Spekulatius\PHPScraper\DataTransferObjects\FeedEntry;
class FeedSearchIndexTest extends \PHPUnit\Framework\TestCase
{
/**
* @test
*/
public function testSearchIndexUrl()
{
$web = new \Spekulatius\PHPScraper\PHPScraper;
// Navigate to the test page. As the URL is predefined, it's only about the base URL.
$web->go('https://test-pages.phpscraper.de/meta/feeds.html');
// Did we get the expected `/index.json`?
$this->assertSame(
'https://test-pages.phpscraper.de/index.json',
$web->searchIndexUrl
);
}
/**
* Tests if the default search index path is applied.
*
* @test
*/
public function testDefaultSearchIndexUrl()
{
$web = new \Spekulatius\PHPScraper\PHPScraper;
// Navigate to the test page. As the URL is predefined, it's only about the base URL.
$web->go('https://test-pages.phpscraper.de/meta/feeds.html');
// `searchIndexUrl` should be the default.
$this->assertSame(
$web->searchIndexRaw(),
$web->searchIndexRaw($web->searchIndexUrl),
);
}
/**
* The `custom_index.json` and `index.json` are the same.
*
* So we compare the two results to ensure the custom URL feature works.
*
* @test
*/
public function testCustomSearchIndexUrl()
{
$web = new \Spekulatius\PHPScraper\PHPScraper;
// Navigate to the test page. As the URL is predefined, it's only about the base URL.
$web->go('https://test-pages.phpscraper.de/meta/feeds.html');
// We should always allow for custom urls.
$this->assertSame(
$web->searchIndexRaw($web->searchIndexUrl),
$web->searchIndexRaw($web->currentBaseHost . '/custom_index.json'),
);
}
/**
* We should support both absolute and relative URLs.
*
* @test
*/
public function testDifferentSearchIndexUrlTypes()
{
$web = new \Spekulatius\PHPScraper\PHPScraper;
// Navigate to the test page. As the URL is predefined, it's only about the base URL.
$web->go('https://test-pages.phpscraper.de/meta/feeds.html');
// Test 1: Absolute URL
$this->assertSame(
$web->searchIndexRaw($web->searchIndexUrl),
$web->searchIndexRaw($web->currentBaseHost . '/custom_index.json'),
);
// Test 2: Relative URL
$this->assertSame(
$web->searchIndexRaw($web->searchIndexUrl),
$web->searchIndexRaw('/custom_index.json'),
);
}
/**
* Tests the raw parsing.
*
* @test
*/
public function testSearchIndexRaw()
{
$web = new \Spekulatius\PHPScraper\PHPScraper;
// Navigate to the test page. As the URL is predefined, it's only about the base URL.
$web->go('https://test-pages.phpscraper.de/meta/feeds.html');
// Get the raw searchIndex and store it.
$searchIndexRaw = $web->searchIndexRaw;
// Ensure the structure is an nested array
$this->assertTrue(is_array($searchIndexRaw));
$this->assertTrue(is_array($searchIndexRaw[42]));
// Did we get the expected `/index.json`? It should contain 60 entries.
$this->assertSame(60, count($searchIndexRaw));
// Check some data to ensure the parsing actually worked.
$this->assertSame(
'https://pastablelists.com/en/counties-of-croatia',
$searchIndexRaw[4]['link']
);
$this->assertSame(
'https://pastablelists.com/en/municipalities-of-macedonia',
$searchIndexRaw[2]['link']
);
$this->assertSame(
'https://pastablelists.com/en/counties-and-municipalities-of-lithuania',
$searchIndexRaw[0]['link']
);
}
/**
* Tests the DTO creation.
*
* @test
*/
public function testSearchIndex()
{
$web = new \Spekulatius\PHPScraper\PHPScraper;
// Navigate to the test page. As the URL is predefined, it's only about the base URL.
$web->go('https://test-pages.phpscraper.de/meta/feeds.html');
// Get the searchIndex and store it.
$searchIndex = $web->searchIndex;
// Did we get the expected `/index.json`? It should contain 60 entries.
$this->assertSame(60, count($searchIndex));
// Check some data to ensure the parsing actually worked:
// Set 1
$this->assertTrue($searchIndex[4] instanceof FeedEntry);
$this->assertSame(
'List of the Counties of Croatia',
$searchIndex[4]->title,
);
$this->assertSame(
'List of the Counties of Croatia ready for copy and paste or export.',
$searchIndex[4]->description,
);
$this->assertSame(
'https://pastablelists.com/en/counties-of-croatia',
$searchIndex[4]->link,
);
// Set 2
$this->assertTrue($searchIndex[2] instanceof FeedEntry);
$this->assertSame(
'List of the Municipalities of Macedonia',
$searchIndex[2]->title,
);
$this->assertSame(
'List of the Municipalities of Macedonia ready for copy and paste or export.',
$searchIndex[2]->description,
);
$this->assertSame(
'https://pastablelists.com/en/municipalities-of-macedonia',
$searchIndex[2]->link,
);
// Set 3
$this->assertTrue($searchIndex[0] instanceof FeedEntry);
$this->assertSame(
'List of the Counties and Municipalities of Lithuania',
$searchIndex[0]->title,
);
$this->assertSame(
'List of the Counties and Municipalities of Lithuania, ready for copy and paste or export.',
$searchIndex[0]->description,
);
$this->assertSame(
'https://pastablelists.com/en/counties-and-municipalities-of-lithuania',
$searchIndex[0]->link,
);
}
}

View file

@ -0,0 +1,147 @@
<?php
namespace Spekulatius\PHPScraper\Tests;
use Spekulatius\PHPScraper\DataTransferObjects\FeedEntry;
class FeedSitemapTest extends \PHPUnit\Framework\TestCase
{
/**
* @test
*/
public function testSitemapUrl()
{
$web = new \Spekulatius\PHPScraper\PHPScraper;
// Navigate to the test page. As the URL is guessed, it's only about the base URL.
$web->go('https://test-pages.phpscraper.de/meta/feeds.html');
// Did we get the expected `/sitemap.xml`?
$this->assertSame(
'https://test-pages.phpscraper.de/sitemap.xml',
$web->sitemapUrl
);
}
/**
* Tests if the default sitemap path is applied.
*
* @test
*/
public function testDefaultSitemapUrl()
{
$web = new \Spekulatius\PHPScraper\PHPScraper;
// Navigate to the test page. As the URL is guessed, it's only about the base URL.
$web->go('https://test-pages.phpscraper.de/meta/feeds.html');
// The sitemapUrl should be the default.
$this->assertSame(
$web->sitemapRaw(),
$web->sitemapRaw($web->sitemapUrl),
);
}
/**
* The files `sitemap.xml` and `custom_sitemap.xml` are the same and used to ensure the custom URL feature works.
*
* @test
*/
public function testCustomSitemapUrl()
{
$web = new \Spekulatius\PHPScraper\PHPScraper;
// Navigate to the test page. As the URL is guessed, it's only about the base URL.
$web->go('https://test-pages.phpscraper.de/meta/feeds.html');
// We should always allow for custom paths.
$this->assertSame(
$web->sitemapRaw($web->sitemapUrl),
$web->sitemapRaw($web->currentBaseHost . '/custom_sitemap.xml'),
);
}
/**
* We should support both absolute and relative URLs.
*
* @test
*/
public function testDifferentSitemapUrlTypes()
{
$web = new \Spekulatius\PHPScraper\PHPScraper;
// Navigate to the test page. As the URL is predefined, it's only about the base URL.
$web->go('https://test-pages.phpscraper.de/meta/feeds.html');
// Test 1: Absolute URL
$this->assertSame(
$web->sitemapRaw($web->sitemapUrl),
$web->sitemapRaw($web->currentBaseHost . '/custom_sitemap.xml'),
);
// Test 2: Relative URL
$this->assertSame(
$web->sitemapRaw($web->sitemapUrl),
$web->sitemapRaw('/custom_sitemap.xml'),
);
}
/**
* Ensure we can parse the sitemap in itself (XML).
*
* @test
*/
public function testSitemapRaw()
{
$web = new \Spekulatius\PHPScraper\PHPScraper;
// Navigate to the test page. As the URL is guessed, it's only about the base URL.
$web->go('https://test-pages.phpscraper.de/meta/feeds.html');
// Get the sitemap and store it.
$sitemapRaw = $web->sitemapRaw;
// Check the count
$this->assertSame(129, count($sitemapRaw['url']));
// Check some entries to ensure the parsing works as expected.
$this->assertSame(
'https://phpscraper.de/apis/linkedin.html',
$sitemapRaw['url'][4]['loc'],
);
$this->assertSame(
'https://phpscraper.de/de/apis/zalando.html',
$sitemapRaw['url'][20]['loc'],
);
}
/**
* Tests the DTO creation.
*
* @test
*/
public function testSitemap()
{
$web = new \Spekulatius\PHPScraper\PHPScraper;
// Navigate to the test page. As the URL is guessed, it's only about the base URL.
$web->go('https://test-pages.phpscraper.de/meta/feeds.html');
// Get the sitemap and store it.
$sitemap = $web->sitemap;
// Check the count
$this->assertSame(129, count($sitemap));
// Check some samples.
$this->assertTrue($sitemap[42] instanceof FeedEntry);
$this->assertSame(
'https://phpscraper.de/apis/linkedin.html',
$sitemap[4]->link,
);
$this->assertSame(
'https://phpscraper.de/de/apis/zalando.html',
$sitemap[20]->link
);
}
}

View file

@ -0,0 +1,130 @@
<?php
namespace Spekulatius\PHPScraper\Tests;
class HeadingTest extends \PHPUnit\Framework\TestCase
{
/**
* @test
*/
public function testMissingHeadings()
{
$web = new \Spekulatius\PHPScraper\PHPScraper;
// Navigate to the test page.
$web->go('https://test-pages.phpscraper.de/meta/no-meta.html');
// Check the missing headers (h1 actually exists on the page).
$this->assertSame([], $web->h2);
$this->assertSame([], $web->h3);
$this->assertSame([], $web->h4);
$this->assertSame([], $web->h5);
$this->assertSame([], $web->h6);
}
/**
* @test
*/
public function testWithHTMLEntity()
{
$web = new \Spekulatius\PHPScraper\PHPScraper;
// Navigate to the test page.
$web->go('https://test-pages.phpscraper.de/meta/html-entities.html');
// Check the h1
$this->assertSame(
'We are testing here & elsewhere!',
$web->h1[0]
);
// h2s
$this->assertSame(2, count($web->h2));
$this->assertSame([
'Cat & Mouse',
'Mouse & Cat',
], $web->h2);
// Collection of headings
$this->assertSame(
[
['We are testing here & elsewhere!'],
['Cat & Mouse', 'Mouse & Cat'],
['1', '2', '3'],
['Not so important heading'],
[],
[],
],
$web->headings
);
}
/**
* @test
*/
public function testLoremIpsum()
{
$web = new \Spekulatius\PHPScraper\PHPScraper;
// Navigate to the test page.
$web->go('https://test-pages.phpscraper.de/meta/lorem-ipsum.html');
// Check the h1
$this->assertSame(
'We are testing here!',
$web->h1[0]
);
// h2s
$this->assertSame(2, count($web->h2));
$this->assertSame([
'h2s are headings too.',
'h2s are headings too.',
], $web->h2);
}
/**
* @test
*/
public function testGermanUmlaute()
{
$web = new \Spekulatius\PHPScraper\PHPScraper;
// Navigate to the test page.
$web->go('https://test-pages.phpscraper.de/meta/german-umlaute.html');
// Check the h1
$this->assertSame(
'We are testing here ä ü ö!',
$web->h1[0]
);
// h2s
$this->assertSame(2, count($web->h2));
$this->assertSame([
'Täst, ehm, test!',
'Weiter testen, Müller!',
], $web->h2);
}
/**
* @test
*/
public function testChineseCharacters()
{
$web = new \Spekulatius\PHPScraper\PHPScraper;
// Navigate to the test page.
$web->go('https://test-pages.phpscraper.de/meta/chinese-characters.html');
// Check the h1
$this->assertSame(
'We are testing here! 加油!',
$web->h1[0]
);
// h2s
$this->assertSame(2, count($web->h2));
$this->assertSame(['加油!', '加油 #1!'], $web->h2);
}
}

243
lib/sc/tests/ImageTest.php Normal file
View file

@ -0,0 +1,243 @@
<?php
namespace Spekulatius\PHPScraper\Tests;
class ImageTest extends \PHPUnit\Framework\TestCase
{
/**
* @test
*/
public function testNoImages()
{
$web = new \Spekulatius\PHPScraper\PHPScraper;
// Navigate to the test page.
$web->go('https://test-pages.phpscraper.de/meta/missing.html');
// No images -> an empty array is expected.
$this->assertSame([], $web->images);
$this->assertSame([], $web->imagesWithDetails);
}
/**
* @test
*/
public function testLoremIpsum()
{
$web = new \Spekulatius\PHPScraper\PHPScraper;
// Navigate to the test page.
$web->go('https://test-pages.phpscraper.de/meta/lorem-ipsum.html');
// Navigate to the test page. This page contains two images (cat.jpg).
$this->assertSame(2, count($web->images));
// Check the simple list
$this->assertSame([
'https://test-pages.phpscraper.de/assets/cat.jpg',
'https://test-pages.phpscraper.de/assets/cat.jpg',
], $web->images);
// Check the expected data
$this->assertSame([
[
'url' => 'https://test-pages.phpscraper.de/assets/cat.jpg',
'alt' => 'absolute path',
'width' => null,
'height' => null,
],
[
'url' => 'https://test-pages.phpscraper.de/assets/cat.jpg',
'alt' => 'relative path',
'width' => null,
'height' => null,
],
], $web->imagesWithDetails);
}
/**
* @test
*/
public function testGermanUmlaute()
{
$web = new \Spekulatius\PHPScraper\PHPScraper;
// Navigate to the test page.
$web->go('https://test-pages.phpscraper.de/meta/german-umlaute.html');
// Check the h1
$this->assertSame(
'We are testing here ä ü ö!',
$web->h1[0]
);
// Check the number of images
$this->assertSame(2, count($web->images));
// Check the simple list
$this->assertSame([
'https://test-pages.phpscraper.de/assets/katze-ä-ü-ö.jpg',
'https://test-pages.phpscraper.de/assets/katze-ä-ü-ö.jpg',
], $web->images);
// Check the expected data
$this->assertSame([
[
'url' => 'https://test-pages.phpscraper.de/assets/katze-ä-ü-ö.jpg',
'alt' => 'absolute path',
'width' => null,
'height' => null,
],
[
'url' => 'https://test-pages.phpscraper.de/assets/katze-ä-ü-ö.jpg',
'alt' => 'relative path',
'width' => null,
'height' => null,
],
], $web->imagesWithDetails);
}
/**
* @test
*/
public function testChineseCharacters()
{
$web = new \Spekulatius\PHPScraper\PHPScraper;
// Navigate to the test page.
$web->go('https://test-pages.phpscraper.de/meta/chinese-characters.html');
// Check the number of images
$this->assertSame(2, count($web->images));
// Check the simple list
$this->assertSame([
'https://test-pages.phpscraper.de/assets/貓.jpg',
'https://test-pages.phpscraper.de/assets/貓.jpg',
], $web->images);
// Check the expected data
$this->assertSame([
[
'url' => 'https://test-pages.phpscraper.de/assets/貓.jpg',
'alt' => 'absolute path',
'width' => null,
'height' => null,
],
[
'url' => 'https://test-pages.phpscraper.de/assets/貓.jpg',
'alt' => 'relative path',
'width' => null,
'height' => null,
],
], $web->imagesWithDetails);
}
/**
* @test
*/
public function testBaseHref()
{
$web = new \Spekulatius\PHPScraper\PHPScraper;
// Navigate to the test page.
$web->go('https://test-pages.phpscraper.de/images/base-href.html');
// Check the number of images
$this->assertSame(2, count($web->images));
// Base set:
$this->assertSame([
'https://test-pages.phpscraper.de/assets/cat.jpg',
'https://test-pages-with-base-href.phpscraper.de/assets/cat.jpg',
], $web->images);
// Detail set:
$this->assertSame([
[
'url' => 'https://test-pages.phpscraper.de/assets/cat.jpg',
'alt' => 'absolute path with base href',
'width' => null,
'height' => null,
],
[
'url' => 'https://test-pages-with-base-href.phpscraper.de/assets/cat.jpg',
'alt' => 'relative path with base href',
'width' => null,
'height' => null,
],
], $web->imagesWithDetails);
}
/**
* @test
*/
public function testWidth()
{
$web = new \Spekulatius\PHPScraper\PHPScraper;
// Navigate to the test page.
$web->go('https://test-pages.phpscraper.de/images/width.html');
// Check the number of images
$this->assertSame(3, count($web->images));
// Check the expected data
$this->assertSame([
[
'url' => 'https://test-pages.phpscraper.de/assets/cat.jpg',
'alt' => 'no width',
'width' => null,
'height' => null,
],
[
'url' => 'https://test-pages.phpscraper.de/assets/cat.jpg',
'alt' => 'width at 1200px',
'width' => '1200px',
'height' => null,
],
[
'url' => 'https://test-pages.phpscraper.de/assets/cat.jpg',
'alt' => 'width at 100rem',
'width' => '100rem',
'height' => null,
],
], $web->imagesWithDetails);
}
/**
* @test
*/
public function testHeight()
{
$web = new \Spekulatius\PHPScraper\PHPScraper;
// Navigate to the test page.
$web->go('https://test-pages.phpscraper.de/images/height.html');
// Check the number of imagess
$this->assertSame(3, count($web->images));
// Check the expected data
$this->assertSame([
[
'url' => 'https://test-pages.phpscraper.de/assets/cat.jpg',
'alt' => 'no height',
'width' => null,
'height' => null,
],
[
'url' => 'https://test-pages.phpscraper.de/assets/cat.jpg',
'alt' => 'height at 1200px',
'width' => null,
'height' => '1200px',
],
[
'url' => 'https://test-pages.phpscraper.de/assets/cat.jpg',
'alt' => 'height at 100rem',
'width' => null,
'height' => '100rem',
],
], $web->imagesWithDetails);
}
}

View file

@ -0,0 +1,91 @@
<?php
namespace Spekulatius\PHPScraper\Tests;
class KeywordTest extends \PHPUnit\Framework\TestCase
{
/**
* @test
*/
public function testKeywordExtraction()
{
$web = new \Spekulatius\PHPScraper\PHPScraper;
// Navigate to the test page.
// It contains 3 paragraphs from the English Wikipedia article for "lorem ipsum"
$web->go('https://test-pages.phpscraper.de/content/keywords.html');
// Check the keywords on this case...
$keywords = $web->contentKeywords;
// A selected list of keywords to expect
$shouldKeywords = [
'1960s',
'added',
'adopted lorem ipsum',
'advertisements',
'aldus employed',
'corrupted version',
'graphic',
'improper latin',
'introduced',
'keyword extraction tests',
'test',
'microsoft word',
'english wikipedia',
'lorem ipsum',
'lorem ipsum text',
];
// Check if all are part of the output
foreach ($shouldKeywords as $keyword) {
$this->assertTrue(
in_array($keyword, $keywords),
sprintf('"%s" is missing', $keyword)
);
}
}
/**
* @test
*/
public function testKeywordExtractionWithScores()
{
$web = new \Spekulatius\PHPScraper\PHPScraper;
// Navigate to the test page.
// It contains 3 paragraphs from the English Wikipedia article for "lorem ipsum"
$web->go('https://test-pages.phpscraper.de/content/keywords.html');
// Check the keywords on this case...
$keywords = $web->contentKeywordsWithScores;
// A selected list of keywords to expect
$shouldKeywords = [
'added' => 1.0,
'adopted lorem ipsum' => 11.0,
'advertisements' => 1.0,
'aldus employed' => 4.0,
'corrupted version' => 4.0,
'graphic' => 1.0,
'improper latin' => 4.0,
'introduced' => 1.0,
'keyword extraction tests' => 9.0,
'test' => 1.0,
'microsoft word' => 5.3333333333333,
'english wikipedia' => 4.0,
'lorem ipsum' => 8.0,
'lorem ipsum text' => 11.0,
];
// Check if all are part of the output with the expected score
foreach ($shouldKeywords as $keyword => $score) {
// Has the same score
$this->assertSame(
round($keywords[$keyword], 8),
round($score, 8),
sprintf('Score for "%s" is incorrect', $keyword)
);
}
}
}

406
lib/sc/tests/LinkTest.php Normal file
View file

@ -0,0 +1,406 @@
<?php
namespace Spekulatius\PHPScraper\Tests;
class LinkTest extends \PHPUnit\Framework\TestCase
{
/**
* @test
*/
public function testNoLinks()
{
$web = new \Spekulatius\PHPScraper\PHPScraper;
// Navigate to the test page.
$web->go('https://test-pages.phpscraper.de/links/no-links.html');
// No links -> an empty array is expected.
$this->assertSame([], $web->links);
$this->assertSame([], $web->linksWithDetails);
}
/**
* @test
*/
public function testTarget()
{
$web = new \Spekulatius\PHPScraper\PHPScraper;
// Navigate to the test page.
$web->go('https://test-pages.phpscraper.de/links/target.html');
// Check the number of links
$this->assertSame(6, count($web->links));
// Check the simple links list
$this->assertSame([
'https://placekitten.com/408/287',
'https://placekitten.com/444/333',
'https://placekitten.com/444/321',
'https://placekitten.com/408/287',
'https://placekitten.com/444/333',
'https://placekitten.com/444/321',
], $web->links);
// Check the complex links list
$this->assertSame([
[
'url' => 'https://placekitten.com/408/287',
'protocol' => 'https',
'text' => 'external kitten',
'title' => null,
'target' => '_blank',
'rel' => null,
'image' => [],
'isNofollow' => false,
'isUGC' => false,
'isSponsored' => false,
'isMe' => false,
'isNoopener' => false,
'isNoreferrer' => false,
], [
'url' => 'https://placekitten.com/444/333',
'protocol' => 'https',
'text' => 'external kitten',
'title' => null,
'target' => '_blank',
'rel' => null,
'image' => [],
'isNofollow' => false,
'isUGC' => false,
'isSponsored' => false,
'isMe' => false,
'isNoopener' => false,
'isNoreferrer' => false,
], [
'url' => 'https://placekitten.com/444/321',
'protocol' => 'https',
'text' => 'external kitten',
'title' => null,
'target' => '_blank',
'rel' => null,
'image' => [],
'isNofollow' => false,
'isUGC' => false,
'isSponsored' => false,
'isMe' => false,
'isNoopener' => false,
'isNoreferrer' => false,
], [
'url' => 'https://placekitten.com/408/287',
'protocol' => 'https',
'text' => 'external kitten',
'title' => null,
'target' => 'kitten',
'rel' => null,
'image' => [],
'isNofollow' => false,
'isUGC' => false,
'isSponsored' => false,
'isMe' => false,
'isNoopener' => false,
'isNoreferrer' => false,
], [
'url' => 'https://placekitten.com/444/333',
'protocol' => 'https',
'text' => 'external kitten',
'title' => null,
'target' => 'kitten',
'rel' => null,
'image' => [],
'isNofollow' => false,
'isUGC' => false,
'isSponsored' => false,
'isMe' => false,
'isNoopener' => false,
'isNoreferrer' => false,
], [
'url' => 'https://placekitten.com/444/321',
'protocol' => 'https',
'text' => 'external kitten',
'title' => null,
'target' => 'kitten',
'rel' => null,
'image' => [],
'isNofollow' => false,
'isUGC' => false,
'isSponsored' => false,
'isMe' => false,
'isNoopener' => false,
'isNoreferrer' => false,
],
], $web->linksWithDetails);
}
/**
* @test
*/
public function testRel()
{
$web = new \Spekulatius\PHPScraper\PHPScraper;
// Navigate to the test page.
// This page contains several links with different rel attributes.
$web->go('https://test-pages.phpscraper.de/links/rel.html');
// Check the number of links
$this->assertSame(5, count($web->links));
// Check the simple links list
$this->assertSame([
'https://placekitten.com/432/287',
'https://placekitten.com/456/287',
'https://placekitten.com/345/287',
'https://placekitten.com/345/287',
'https://placekitten.com/345/222',
], $web->links);
// Check the complex links list
$this->assertSame([
[
'url' => 'https://placekitten.com/432/287',
'protocol' => 'https',
'text' => 'external kitten',
'title' => null,
'target' => null,
'rel' => 'nofollow',
'image' => [],
'isNofollow' => true,
'isUGC' => false,
'isSponsored' => false,
'isMe' => false,
'isNoopener' => false,
'isNoreferrer' => false,
], [
'url' => 'https://placekitten.com/456/287',
'protocol' => 'https',
'text' => 'external kitten',
'title' => null,
'target' => null,
'rel' => 'ugc',
'image' => [],
'isNofollow' => false,
'isUGC' => true,
'isSponsored' => false,
'isMe' => false,
'isNoopener' => false,
'isNoreferrer' => false,
], [
'url' => 'https://placekitten.com/345/287',
'protocol' => 'https',
'text' => 'external kitten',
'title' => null,
'target' => null,
'rel' => 'nofollow ugc',
'image' => [],
'isNofollow' => true,
'isUGC' => true,
'isSponsored' => false,
'isMe' => false,
'isNoopener' => false,
'isNoreferrer' => false,
], [
'url' => 'https://placekitten.com/345/287',
'protocol' => 'https',
'text' => 'external kitten',
'title' => null,
'target' => null,
'rel' => 'noopener',
'image' => [],
'isNofollow' => false,
'isUGC' => false,
'isSponsored' => false,
'isMe' => false,
'isNoopener' => true,
'isNoreferrer' => false,
], [
'url' => 'https://placekitten.com/345/222',
'protocol' => 'https',
'text' => 'external kitten',
'title' => null,
'target' => null,
'rel' => 'noreferrer',
'image' => [],
'isNofollow' => false,
'isUGC' => false,
'isSponsored' => false,
'isMe' => false,
'isNoopener' => false,
'isNoreferrer' => true,
],
], $web->linksWithDetails);
}
/**
* @test
*/
public function testBaseHref()
{
$web = new \Spekulatius\PHPScraper\PHPScraper;
// Navigate to the test page.
$web->go('https://test-pages.phpscraper.de/links/base-href.html');
// Check the number of links
$this->assertSame(3, count($web->links));
// Check the simple links list
$this->assertSame([
'https://placekitten.com/408/287',
'https://test-pages.phpscraper.de/assets/cat.jpg',
'https://test-pages-with-base-href.phpscraper.de/assets/cat.jpg',
], $web->links);
// Check the complex links list
$this->assertSame([
[
'url' => 'https://placekitten.com/408/287',
'protocol' => 'https',
'text' => 'external kitten',
'title' => 'external path with base href',
'target' => null,
'rel' => null,
'image' => [],
'isNofollow' => false,
'isUGC' => false,
'isSponsored' => false,
'isMe' => false,
'isNoopener' => false,
'isNoreferrer' => false,
], [
'url' => 'https://test-pages.phpscraper.de/assets/cat.jpg',
'protocol' => 'https',
'text' => 'absolute path to cat',
'title' => 'absolute internal path with base href',
'target' => null,
'rel' => null,
'image' => [],
'isNofollow' => false,
'isUGC' => false,
'isSponsored' => false,
'isMe' => false,
'isNoopener' => false,
'isNoreferrer' => false,
], [
'url' => 'https://test-pages-with-base-href.phpscraper.de/assets/cat.jpg',
'protocol' => 'https',
'text' => 'relative cat',
'title' => 'relative path with base href',
'target' => null,
'rel' => null,
'image' => [],
'isNofollow' => false,
'isUGC' => false,
'isSponsored' => false,
'isMe' => false,
'isNoopener' => false,
'isNoreferrer' => false,
],
], $web->linksWithDetails);
}
/**
* @test
*/
public function testImageUrl()
{
$web = new \Spekulatius\PHPScraper\PHPScraper;
// Navigate to the test page.
$web->go('https://test-pages.phpscraper.de/links/image-url.html');
// Check the number of links
$this->assertSame(3, count($web->links));
// Check the complex links list
$this->assertSame([
[
'url' => 'https://placekitten.com/432/500',
'protocol' => 'https',
'text' => '',
'title' => null,
'target' => null,
'rel' => 'nofollow',
'image' => [
'https://placekitten.com/432/287',
],
'isNofollow' => true,
'isUGC' => false,
'isSponsored' => false,
'isMe' => false,
'isNoopener' => false,
'isNoreferrer' => false,
], [
'url' => 'https://placekitten.com/456/500',
'protocol' => 'https',
'text' => '',
'title' => null,
'target' => null,
'rel' => 'ugc',
'image' => [
'https://placekitten.com/456/400',
'https://placekitten.com/456/300',
],
'isNofollow' => false,
'isUGC' => true,
'isSponsored' => false,
'isMe' => false,
'isNoopener' => false,
'isNoreferrer' => false,
], [
'url' => 'https://placekitten.com/345/500',
'protocol' => 'https',
'text' => 'This is image',
'title' => null,
'target' => null,
'rel' => 'nofollow ugc',
'image' => [
'https://placekitten.com/345/287',
],
'isNofollow' => true,
'isUGC' => true,
'isSponsored' => false,
'isMe' => false,
'isNoopener' => false,
'isNoreferrer' => false,
],
], $web->linksWithDetails);
}
/**
* @test
*/
public function testInternalLinks()
{
$web = new \Spekulatius\PHPScraper\PHPScraper;
// Navigate to the test page.
$web->go('https://test-pages.phpscraper.de/links/base-href.html');
// Check the internal links list
$this->assertSame(
['https://test-pages.phpscraper.de/assets/cat.jpg'],
$web->internalLinks
);
}
/**
* @test
*/
public function testExternalLinks()
{
$web = new \Spekulatius\PHPScraper\PHPScraper;
// Navigate to the test page.
$web->go('https://test-pages.phpscraper.de/links/base-href.html');
// Check the external links list
$this->assertSame(
[
'https://placekitten.com/408/287',
'https://test-pages-with-base-href.phpscraper.de/assets/cat.jpg',
],
$web->externalLinks
);
}
}

View file

@ -0,0 +1,51 @@
<?php
namespace Spekulatius\PHPScraper\Tests;
class ListsTest extends \PHPUnit\Framework\TestCase
{
/**
* @test
*/
public function checkCountTest()
{
$web = new \Spekulatius\PHPScraper\PHPScraper;
/**
* Navigate to the test page. This page contains:
*
* <h2>Example 1: Unordered List</h2>
* <ul>
* <li>Unordered item 1</li>
* <li>Unordered item 2</li>
* <li>Unordered item with <b>HTML</b></li>
* </ul>
*
* <h2>Example 2: Ordered List</h2>
* <ol>
* <li>Order list item 1</li>
* <li>Order list item 2</li>
* <li>Order list item with <i>HTML</i></li>
* </ol>
*/
$web->go('https://test-pages.phpscraper.de/content/lists.html');
// Check all lists are recognized
$this->assertSame(count($web->lists), 2);
$this->assertSame(count($web->unorderedLists), 1);
$this->assertSame(count($web->orderedLists), 1);
// Check the contents
$this->assertSame([
'Ordered list item 1',
'Ordered list item 2',
'Ordered list item with HTML',
], $web->orderedLists[0]['children_plain']);
$this->assertSame([
'Unordered list item 1',
'Unordered list item 2',
'Unordered list item with HTML',
], $web->unorderedLists[0]['children_plain']);
}
}

View file

@ -0,0 +1,88 @@
<?php
namespace Spekulatius\PHPScraper\Tests;
class MetaAuthorTest extends \PHPUnit\Framework\TestCase
{
/**
* @test
*/
public function testMissingAuthor()
{
$web = new \Spekulatius\PHPScraper\PHPScraper;
// Navigate to the test page.
$web->go('https://test-pages.phpscraper.de/meta/meta/missing.html');
// Check the author as not given (null)
$this->assertNull($web->author);
}
/**
* @test
*/
public function testWithHTMLEntity()
{
$web = new \Spekulatius\PHPScraper\PHPScraper;
// Navigate to the test page.
$web->go('https://test-pages.phpscraper.de/meta/html-entities.html');
// Check the author
$this->assertSame(
'Cat & Mouse',
$web->author
);
}
/**
* @test
*/
public function testLoremIpsum()
{
$web = new \Spekulatius\PHPScraper\PHPScraper;
// Navigate to the test page.
$web->go('https://test-pages.phpscraper.de/meta/lorem-ipsum.html');
// Check the author
$this->assertSame(
'Lorem ipsum',
$web->author
);
}
/**
* @test
*/
public function testGermanUmlaute()
{
$web = new \Spekulatius\PHPScraper\PHPScraper;
// Navigate to the test page.
$web->go('https://test-pages.phpscraper.de/meta/german-umlaute.html');
// Check the author
$this->assertSame(
'Müller',
$web->author
);
}
/**
* @test
*/
public function testChineseCharacters()
{
$web = new \Spekulatius\PHPScraper\PHPScraper;
// Navigate to the test page.
$web->go('https://test-pages.phpscraper.de/meta/chinese-characters.html');
// Check the author
$this->assertSame(
'貓',
$web->author
);
}
}

View file

@ -0,0 +1,37 @@
<?php
namespace Spekulatius\PHPScraper\Tests;
class MetaCharsetTest extends \PHPUnit\Framework\TestCase
{
/**
* @test
*/
public function testMissingCharset()
{
$web = new \Spekulatius\PHPScraper\PHPScraper;
// Navigate to the test page.
$web->go('https://test-pages.phpscraper.de/meta/missing.html');
// Check the charset as not given (null)
$this->assertNull($web->charset);
}
/**
* @test
*/
public function testWithCharset()
{
$web = new \Spekulatius\PHPScraper\PHPScraper;
// Navigate to the test page.
$web->go('https://test-pages.phpscraper.de/meta/lorem-ipsum.html');
// Check the charset
$this->assertSame(
'utf-8',
$web->charset
);
}
}

View file

@ -0,0 +1,37 @@
<?php
namespace Spekulatius\PHPScraper\Tests;
class MetaContentTypeTest extends \PHPUnit\Framework\TestCase
{
/**
* @test
*/
public function testMissingContentType()
{
$web = new \Spekulatius\PHPScraper\PHPScraper;
// Navigate to the test page.
$web->go('https://test-pages.phpscraper.de/meta/missing.html');
// Check the contentType as not given (null)
$this->assertNull($web->contentType);
}
/**
* @test
*/
public function testWithContentType()
{
$web = new \Spekulatius\PHPScraper\PHPScraper;
// Navigate to the test page.
$web->go('https://test-pages.phpscraper.de/meta/lorem-ipsum.html');
// Check the contentType
$this->assertSame(
'text/html; charset=utf-8',
$web->contentType
);
}
}

View file

@ -0,0 +1,38 @@
<?php
namespace Spekulatius\PHPScraper\Tests;
class MetaCsrfTokenTest extends \PHPUnit\Framework\TestCase
{
/**
* @test
*/
public function testMissingCsrfToken()
{
$web = new \Spekulatius\PHPScraper\PHPScraper;
// Navigate to the test page.
$web->go('https://test-pages.phpscraper.de/meta/missing.html');
// Check the csrfToken as not given (null)
$this->assertNull($web->csrfToken);
}
/**
* @test
*/
public function testWithCsrfToken()
{
$web = new \Spekulatius\PHPScraper\PHPScraper;
// Navigate to the test page.
// Contains: <meta name="csrf-token" content="token" />
$web->go('https://test-pages.phpscraper.de/meta/lorem-ipsum.html');
// Check the csrfToken
$this->assertSame(
'token',
$web->csrfToken
);
}
}

View file

@ -0,0 +1,88 @@
<?php
namespace Spekulatius\PHPScraper\Tests;
class MetaDescriptionTest extends \PHPUnit\Framework\TestCase
{
/**
* @test
*/
public function testMissingDescription()
{
$web = new \Spekulatius\PHPScraper\PHPScraper;
// Navigate to the test page.
$web->go('https://test-pages.phpscraper.de/meta/missing.html');
// Check the description as not given (null)
$this->assertNull($web->description);
}
/**
* @test
*/
public function testWithHTMLEntity()
{
$web = new \Spekulatius\PHPScraper\PHPScraper;
// Navigate to the test page.
$web->go('https://test-pages.phpscraper.de/meta/html-entities.html');
// Check the description
$this->assertSame(
'Cat & Mouse',
$web->description
);
}
/**
* @test
*/
public function testLoremIpsum()
{
$web = new \Spekulatius\PHPScraper\PHPScraper;
// Navigate to the test page.
$web->go('https://test-pages.phpscraper.de/meta/lorem-ipsum.html');
// Check the description
$this->assertSame(
'Lorem ipsum dolor etc.',
$web->description
);
}
/**
* @test
*/
public function testGermanUmlaute()
{
$web = new \Spekulatius\PHPScraper\PHPScraper;
// Navigate to the test page.
$web->go('https://test-pages.phpscraper.de/meta/german-umlaute.html');
// Check the description
$this->assertSame(
'Eine deutsche Beschreibung mit Umlauten: ä ü ö',
$web->description
);
}
/**
* @test
*/
public function testChineseCharacters()
{
$web = new \Spekulatius\PHPScraper\PHPScraper;
// Navigate to the test page.
$web->go('https://test-pages.phpscraper.de/meta/chinese-characters.html');
// Check the description
$this->assertSame(
'A description with Chinese Characters: 加油',
$web->description
);
}
}

View file

@ -0,0 +1,99 @@
<?php
namespace Spekulatius\PHPScraper\Tests;
class MetaImageTest extends \PHPUnit\Framework\TestCase
{
/**
* @test
*/
public function testCallMethodsAreEqual()
{
$web = new \Spekulatius\PHPScraper\PHPScraper;
// Attempt to my blog
$web->go('https://peterthaleikis.com');
// Both the method call as well as property call should return the same...
$this->assertSame($web->image(), $web->image);
}
/**
* @test
*/
public function testMissingImage()
{
$web = new \Spekulatius\PHPScraper\PHPScraper;
// Navigate to the test page.
$web->go('https://test-pages.phpscraper.de/meta/missing.html');
// Check the absolute image path
$this->assertNull($web->image);
}
/**
* @test
*/
public function testAbsolutePath()
{
$web = new \Spekulatius\PHPScraper\PHPScraper;
// Navigate to the test page.
$web->go('https://test-pages.phpscraper.de/meta/image/absolute-path.html');
// Check the absolute image path
$this->assertSame('https://test-pages.phpscraper.de/assets/cat.jpg', $web->image);
}
/**
* @test
*/
public function testRelativePath()
{
$web = new \Spekulatius\PHPScraper\PHPScraper;
// Navigate to the test page.
$web->go('https://test-pages.phpscraper.de/meta/image/relative-path.html');
// Check the relative image path should be converted into an absolute path.
$this->assertSame(
'https://test-pages.phpscraper.de/assets/cat.jpg',
$web->image
);
}
/**
* @test
*/
public function testAbsolutePathWithBaseHref()
{
$web = new \Spekulatius\PHPScraper\PHPScraper;
// Navigate to the test page.
$web->go('https://test-pages.phpscraper.de/meta/image/absolute-path-with-base-href.html');
// Check the absolute image path
$this->assertSame(
'https://test-pages.phpscraper.de/assets/cat.jpg',
$web->image
);
}
/**
* @test
*/
public function testRelativePathBaseHref()
{
$web = new \Spekulatius\PHPScraper\PHPScraper;
// Navigate to the test page.
$web->go('https://test-pages.phpscraper.de/meta/image/relative-path-with-base-href.html');
// Check the relative image path
$this->assertSame(
'https://test-pages-with-base-href.phpscraper.de/assets/cat.jpg',
$web->image
);
}
}

View file

@ -0,0 +1,125 @@
<?php
namespace Spekulatius\PHPScraper\Tests;
class MetaKeywordsTest extends \PHPUnit\Framework\TestCase
{
/**
* @test
*/
public function testMissingKeywords()
{
$web = new \Spekulatius\PHPScraper\PHPScraper;
// Go to the test page
$web->go('https://test-pages.phpscraper.de/meta/missing.html');
// null if there aren't any keywords set.
$this->assertNull($web->keywordString);
// Empty array if there aren't any keywords set.
$this->assertTrue(is_iterable($web->keywords));
$this->assertTrue(empty($web->keywords));
}
/**
* @test
*/
public function testNoSpaces()
{
$web = new \Spekulatius\PHPScraper\PHPScraper;
// Navigate to the test page.
$web->go('https://test-pages.phpscraper.de/meta/keywords/parse-no-spaces.html');
// Check the keywords on this case...
$this->assertSame('one,two,three', $web->keywordString);
$this->assertSame(['one', 'two', 'three'], $web->keywords);
}
/**
* @test
*/
public function testSpaces()
{
$web = new \Spekulatius\PHPScraper\PHPScraper;
// Navigate to the test page.
$web->go('https://test-pages.phpscraper.de/meta/keywords/parse-spaces.html');
// Check the keywords on this case...
$this->assertSame('one, two, three', $web->keywordString);
$this->assertSame(['one', 'two', 'three'], $web->keywords);
}
/**
* @test
*/
public function testIrregularSpaces()
{
$web = new \Spekulatius\PHPScraper\PHPScraper;
// Navigate to the test page.
$web->go('https://test-pages.phpscraper.de/meta/keywords/parse-irregular-spaces.html');
// Check the keywords on this case...
$this->assertSame('one, two, three', $web->keywordString);
$this->assertSame(['one', 'two', 'three'], $web->keywords);
}
/**
* @test
*/
public function testWithHTMLEntity()
{
$web = new \Spekulatius\PHPScraper\PHPScraper;
// Navigate to the test page.
$web->go('https://test-pages.phpscraper.de/meta/html-entities.html');
// Check the keywords
$this->assertSame(['Cat & Mouse', 'Mouse & Cat'], $web->keywords);
}
/**
* @test
*/
public function testLoremIpsum()
{
$web = new \Spekulatius\PHPScraper\PHPScraper;
// Navigate to the test page.
$web->go('https://test-pages.phpscraper.de/meta/lorem-ipsum.html');
// Check the keywords
$this->assertSame(['Lorem', 'ipsum', 'dolor'], $web->keywords);
}
/**
* @test
*/
public function testGermanUmlaute()
{
$web = new \Spekulatius\PHPScraper\PHPScraper;
// Navigate to the test page.
$web->go('https://test-pages.phpscraper.de/meta/german-umlaute.html');
// Check the keywords
$this->assertSame(['keywords', 'schlüsselwörter'], $web->keywords);
}
/**
* @test
*/
public function testChineseCharacters()
{
$web = new \Spekulatius\PHPScraper\PHPScraper;
// Navigate to the test page.
$web->go('https://test-pages.phpscraper.de/meta/chinese-characters.html');
// Check the keywords
$this->assertSame(['加油', '貓'], $web->keywords);
}
}

View file

@ -0,0 +1,45 @@
<?php
namespace Spekulatius\PHPScraper\Tests;
class MetaViewportTest extends \PHPUnit\Framework\TestCase
{
/**
* @test
*/
public function testMissingViewport()
{
$web = new \Spekulatius\PHPScraper\PHPScraper;
// Go to the test page
$web->go('https://test-pages.phpscraper.de/meta/missing.html');
// null if there isn't a viewport set.
$this->assertNull($web->viewportString);
// Empty array if there aren't any viewports set.
$this->assertTrue(is_iterable($web->viewport));
$this->assertTrue(empty($web->viewport));
}
/**
* @test
*/
public function testWithViewport()
{
$web = new \Spekulatius\PHPScraper\PHPScraper;
// Navigate to the test page.
$web->go('https://test-pages.phpscraper.de/meta/lorem-ipsum.html');
// Check the viewport
$this->assertSame(
'width=device-width, initial-scale=1, shrink-to-fit=no, maximum-scale=1, user-scalable=no',
$web->viewportString
);
$this->assertSame(
['width=device-width', 'initial-scale=1', 'shrink-to-fit=no', 'maximum-scale=1', 'user-scalable=no'],
$web->viewport
);
}
}

View file

@ -0,0 +1,132 @@
<?php
namespace Spekulatius\PHPScraper\Tests;
class NavigationTest extends \PHPUnit\Framework\TestCase
{
/**
* @test
*/
public function testSurfWithAbsoluteLink()
{
$web = new \Spekulatius\PHPScraper\PHPScraper;
// Navigate to test page #1.
$web->go('https://test-pages.phpscraper.de/navigation/1.html');
// Check the title to see if we actually at the right page...
$this->assertSame('Page #1', $web->h1[0]);
// Navigate to test page #2 using the absolute link.
$web->clickLink('2 absolute');
// Check the title and URL to see if we actually moved...
$this->assertSame('Page #2', $web->h1[0]);
$this->assertSame($web->currentUrl, 'https://test-pages.phpscraper.de/navigation/2.html');
}
/**
* @test
*/
public function testSurfWithRelativeLink()
{
$web = new \Spekulatius\PHPScraper\PHPScraper;
// Navigate to test page #1.
$web->go('https://test-pages.phpscraper.de/navigation/1.html');
// Check the title to see if we actually at the right page...
$this->assertSame('Page #1', $web->h1[0]);
// Navigate to test page #2 using the relative link.
$web->clickLink('2 relative');
// Check the title and URL to see if we actually moved...
$this->assertSame('Page #2', $web->h1[0]);
$this->assertSame($web->currentUrl, 'https://test-pages.phpscraper.de/navigation/2.html');
}
/**
* Test navigation using an anchor text.
*
* @test
*/
public function testLeavePageByText()
{
$web = new \Spekulatius\PHPScraper\PHPScraper;
// Navigate to test page #2.
$web->go('https://test-pages.phpscraper.de/navigation/2.html');
// Check the title to see if we actually at the right page...
$this->assertSame('Page #2', $web->h1[0]);
// Click the link with the text:
$web->clickLink('external link');
// Check the URL
$this->assertSame('https://peterthaleikis.com/', $web->currentUrl);
}
/**
* Test if we can navigate out using a redirect.
*
* @test
*/
public function testLeavePageWithRedirect()
{
$web = new \Spekulatius\PHPScraper\PHPScraper;
// Navigate to test page #2.
$web->go('https://test-pages.phpscraper.de/navigation/2.html');
// Check the title to see if we actually at the right page...
$this->assertSame('Page #2', $web->h1[0]);
// Click the link with the text:
$web->clickLink('external link with redirect');
// Check the URL
$this->assertSame('https://peterthaleikis.com/', $web->currentUrl);
}
/**
* Test if we can navigate out.
*
* @test
*/
public function testLeavePageByURL()
{
$web = new \Spekulatius\PHPScraper\PHPScraper;
// Navigate to test page #2.
$web->go('https://test-pages.phpscraper.de/navigation/2.html');
// Check the title to see if we actually at the right page...
$this->assertSame('Page #2', $web->h1[0]);
// Click the link with the text:
$web->clickLink('https://peterthaleikis.com/');
// Check the URL
$this->assertSame('https://peterthaleikis.com/', $web->currentUrl);
}
/**
* Test chainability of `clickLink`.
*
* @test
*/
public function testClickLinkChainability()
{
$web = new \Spekulatius\PHPScraper\PHPScraper;
// Navigate to a page, click a link by URL and see if we are on the expected `currentUrl`.
$web
->go('https://test-pages.phpscraper.de/navigation/2.html')
->clickLink('https://peterthaleikis.com/');
// Check the URL
$this->assertSame('https://peterthaleikis.com/', $web->currentUrl);
}
}

View file

@ -0,0 +1,22 @@
<?php
namespace Spekulatius\PHPScraper\Tests;
use PHPUnit\Framework\TestCase;
class NotFoundTest extends TestCase
{
/**
* @test
*/
public function testPageMissing()
{
$web = new \Spekulatius\PHPScraper\PHPScraper;
// Navigate to the test page.
$web->go('https://test-pages.phpscraper.de/page-does-not-exist.html');
// The built-in server returns this string.
$this->assertSame('Page Not Found', $web->title);
}
}

View file

@ -0,0 +1,49 @@
<?php
namespace Spekulatius\PHPScraper\Tests;
class OpenGraphTest extends \PHPUnit\Framework\TestCase
{
/**
* @test
*/
public function testMissingOpenGraph()
{
$web = new \Spekulatius\PHPScraper\PHPScraper;
// Go to the test page
$web->go('https://test-pages.phpscraper.de/meta/missing.html');
// Empty array, because there aren't any open graph props set.
$this->assertTrue(is_iterable($web->openGraph));
$this->assertTrue(empty($web->openGraph));
}
/**
* @test
*/
public function testOpenGraph()
{
$web = new \Spekulatius\PHPScraper\PHPScraper;
// Navigate to the test page.
$web->go('https://test-pages.phpscraper.de/og/example.html');
// Check elements
$this->assertSame('Lorem Ipsum', $web->openGraph['og:title']);
$this->assertSame('Lorem ipsum dolor etc.', $web->openGraph['og:description']);
// The whole set.
$this->assertSame(
[
'og:site_name' => 'Lorem ipsum',
'og:type' => 'website',
'og:title' => 'Lorem Ipsum',
'og:description' => 'Lorem ipsum dolor etc.',
'og:url' => 'https://test-pages.phpscraper.de/meta/lorem-ipsum.html',
'og:image' => 'https://test-pages.phpscraper.de/assets/cat.jpg',
],
$web->openGraph
);
}
}

View file

@ -0,0 +1,129 @@
<?php
namespace Spekulatius\PHPScraper\Tests;
class OutlineTest extends \PHPUnit\Framework\TestCase
{
/**
* @test
*/
public function outlineTest()
{
$web = new \Spekulatius\PHPScraper\PHPScraper;
/**
* Navigate to the test page. This page contains:
*
* <h1>We are testing here!</h1>
* <p>This page contains an example structure to be parsed. It comes with a number of headings and nested paragraphs as an scrape example.</p>
*
* <h2>Examples</h2>
* <p>There are numerous examples on the website. Please check them out to get more context on how scraping works.</p>
*
* <h3>Example 1</h3>
* <p>Here would be an example.</p>
*
* <h3>Example 2</h3>
* <p>Here would be the second example.</p>
*
* <h3>Example 3</h3>
* <p>Here would be another example.</p>
*/
$web->go('https://test-pages.phpscraper.de/content/outline.html');
// Get the content outline
$this->assertSame(
[
[
'tag' => 'h1',
'content' => 'We are testing here!',
], [
'tag' => 'h2',
'content' => 'Examples',
], [
'tag' => 'h3',
'content' => 'Example 1',
], [
'tag' => 'h3',
'content' => 'Example 2',
], [
'tag' => 'h3',
'content' => 'Example 3',
],
],
$web->outline
);
}
/**
* @test
*/
public function outlineWithParagraphsTest()
{
$web = new \Spekulatius\PHPScraper\PHPScraper;
/**
* Navigate to the test page. This page contains:
*
* <h1>We are testing here!</h1>
* <p>This page contains an example structure to be parsed. It comes with a number of headings and nested paragraphs as an scrape example.</p>
*
* <h2>Examples</h2>
* <p>There are numerous examples on the website. Please check them out to get more context on how scraping works.</p>
*
* <h3>Example 1</h3>
* <p>Here would be an example.</p>
*
* <h3>Example 2</h3>
* <p>Here would be the second example.</p>
*
* <h3>Example 3</h3>
* <p>Here would be another example.</p>
*
* <!-- an empty paragraph to check if it gets filtered out correctly -->
* <p></p>
*/
$web->go('https://test-pages.phpscraper.de/content/outline.html');
// Get the content outline
$this->assertSame(
[
[
'tag' => 'h1',
'content' => 'We are testing here!',
], [
'tag' => 'p',
'content' => 'This page contains an example structure to be parsed. It comes with a number of headings and nested paragraphs as an scrape example.',
], [
'tag' => 'h2',
'content' => 'Examples',
], [
'tag' => 'p',
'content' => 'There are numerous examples on the website. Please check them out to get more context on how scraping works.',
], [
'tag' => 'h3',
'content' => 'Example 1',
], [
'tag' => 'p',
'content' => 'Here would be an example.',
], [
'tag' => 'h3',
'content' => 'Example 2',
], [
'tag' => 'p',
'content' => 'Here would be the second example.',
], [
'tag' => 'h3',
'content' => 'Example 3',
], [
'tag' => 'p',
'content' => 'Here would be another example.',
], [
'tag' => 'p',
'content' => '',
],
],
$web->outlineWithParagraphs
);
}
}

View file

@ -0,0 +1,87 @@
<?php
namespace Spekulatius\PHPScraper\Tests;
class ParagraphsTest extends \PHPUnit\Framework\TestCase
{
/**
* @test
*/
public function paragraphTest()
{
$web = new \Spekulatius\PHPScraper\PHPScraper;
/**
* Navigate to the test page. This page contains:
*
* <h1>We are testing here!</h1>
* <p>This page contains an example structure to be parsed. It comes with a number of headings and nested paragraphs as an scrape example.</p>
*
* <h2>Examples</h2>
* <p>There are numerous examples on the website. Please check them out to get more context on how scraping works.</p>
*
* <h3>Example 1</h3>
* <p>Here would be an example.</p>
*
* <h3>Example 2</h3>
* <p>Here would be the second example.</p>
*
* <h3>Example 3</h3>
* <p>Here would be another example.</p>
*
* <!-- an empty paragraph to check if it gets filtered out correctly -->
* <p></p>
*/
$web->go('https://test-pages.phpscraper.de/content/outline.html');
// Get the paragraphs
$this->assertSame([
'This page contains an example structure to be parsed. It comes with a number of headings and nested paragraphs as an scrape example.',
'There are numerous examples on the website. Please check them out to get more context on how scraping works.',
'Here would be an example.',
'Here would be the second example.',
'Here would be another example.',
'',
], $web->paragraphs);
}
/**
* @test
*/
public function cleanParagraphTest()
{
$web = new \Spekulatius\PHPScraper\PHPScraper;
/**
* Navigate to the test page. This page contains:
*
* <h1>We are testing here!</h1>
* <p>This page contains an example structure to be parsed. It comes with a number of headings and nested paragraphs as an scrape example.</p>
*
* <h2>Examples</h2>
* <p>There are numerous examples on the website. Please check them out to get more context on how scraping works.</p>
*
* <h3>Example 1</h3>
* <p>Here would be an example.</p>
*
* <h3>Example 2</h3>
* <p>Here would be the second example.</p>
*
* <h3>Example 3</h3>
* <p>Here would be another example.</p>
*
* <!-- an empty paragraph to check if it gets filtered out correctly -->
* <p></p>
*/
$web->go('https://test-pages.phpscraper.de/content/outline.html');
// Get the cleaned up paragraphs
$this->assertSame([
'This page contains an example structure to be parsed. It comes with a number of headings and nested paragraphs as an scrape example.',
'There are numerous examples on the website. Please check them out to get more context on how scraping works.',
'Here would be an example.',
'Here would be the second example.',
'Here would be another example.',
], $web->cleanParagraphs);
}
}

View file

@ -0,0 +1,408 @@
<?php
namespace Spekulatius\PHPScraper\Tests;
class ParserCsvTest extends \PHPUnit\Framework\TestCase
{
/**
* @test
*/
public function testCsvParsingContext()
{
$web = new \Spekulatius\PHPScraper\PHPScraper;
// This tests ensures an exception is thrown, if no context is given.
// Context means either it's been navigated before (URL context) or get something to (fetch +) parse
try {
$web = new \Spekulatius\PHPScraper\PHPScraper;
$web->parseCsv();
} catch (\Exception $e) {
// Did we get the expected exception?
$this->assertSame(
'You can not call parseCsv() without parameter or initial navigation.',
$e->getMessage()
);
}
// This tests ensures an exception is thrown, if no context is given.
// Context means either it's been navigated before (URL context) or get something to (fetch +) parse
try {
$web = new \Spekulatius\PHPScraper\PHPScraper;
$web->parseCsvWithHeader();
} catch (\Exception $e) {
// Did we get the expected exception?
$this->assertSame(
'You can not call parseCsvWithHeader() without parameter or initial navigation.',
$e->getMessage()
);
}
}
/**
* @test
*/
public function testCsvDecodeRaw()
{
$web = new \Spekulatius\PHPScraper\PHPScraper;
// Only decoding
$this->assertSame(
[
['date', 'value'],
['1945-02-06', '4.20'],
['1952-03-11', '42'],
],
$web->csvDecodeRaw("date,value\n1945-02-06,4.20\n1952-03-11,42"),
);
// Fetching and decoding
$this->assertSame(
[
['date', 'value'],
['1945-02-06', '4.20'],
['1952-03-11', '42'],
],
$web->csvDecodeRaw($web->fetchAsset('https://test-pages.phpscraper.de/test.csv')),
);
}
/**
* @test
*/
public function testCsvDecode()
{
$web = new \Spekulatius\PHPScraper\PHPScraper;
// Only decoding
$this->assertSame(
[
['date', 'value'],
['1945-02-06', 4.20],
['1952-03-11', 42],
],
$web->csvDecode("date,value\n1945-02-06,4.20\n1952-03-11,42"),
);
// Fetching and decoding
$this->assertSame(
[
['date', 'value'],
['1945-02-06', 4.20],
['1952-03-11', 42],
],
$web->csvDecode($web->fetchAsset('https://test-pages.phpscraper.de/test.csv')),
);
}
/**
* Test with pipe as separator, enclosure and escape.
*
* @test
*/
public function testCsvDecodeAndCustomEncoding()
{
$web = new \Spekulatius\PHPScraper\PHPScraper;
$this->assertSame(
[
['date', 'value'],
['1945-02-06', 4.20],
['1952-03-11', 42],
['\\'],
],
$web->csvDecode(
"\"date\"|\"value\"\n\"1945-02-06\"|\"4.20\"\n\"1952-03-11\"|\"42\"\n\\",
'|',
'"',
'\\'
)
);
}
/**
* @test
*/
public function testCsvDecodeWithHeaderRaw()
{
$web = new \Spekulatius\PHPScraper\PHPScraper;
// Only decoding
$this->assertSame(
[
['date' => '1945-02-06', 'value' => '4.20'],
['date' => '1952-03-11', 'value' => '42'],
],
$web->csvDecodeWithHeaderRaw("date,value\n1945-02-06,4.20\n1952-03-11,42"),
);
// Fetching and decoding
$this->assertSame(
[
['date' => '1945-02-06', 'value' => '4.20'],
['date' => '1952-03-11', 'value' => '42'],
],
$web->csvDecodeWithHeaderRaw($web->fetchAsset('https://test-pages.phpscraper.de/test.csv')),
);
}
/**
* @test
*/
public function testCsvDecodeWithHeaderAndCasting()
{
$web = new \Spekulatius\PHPScraper\PHPScraper;
$this->assertSame(
[
['date' => '1945-02-06', 'value' => 4.20],
['date' => '1952-03-11', 'value' => 42],
],
$web->csvDecodeWithHeader("date,value\n1945-02-06,4.20\n1952-03-11,42"),
);
}
/**
* Test with header, pipe as separator, and enclosure.
*
* @test
*/
public function testCsvDecodeWithHeaderAndCustomEncoding()
{
$web = new \Spekulatius\PHPScraper\PHPScraper;
$this->assertSame(
[
['date' => '1945-02-06', 'value' => 4.20],
['date' => '1952-03-11', 'value' => 42],
],
$web->csvDecodeWithHeader(
"\"date\"|\"value\"\n\"1945-02-06\"|\"4.20\"\n\"1952-03-11\"|\"42\"",
'|',
'"',
'\\'
)
);
}
/**
* Check the pluming: Test the various ways to call `parseCsv()`.
*
* @test
*/
public function testDifferentCsvCalls()
{
// Downloads the PHPScraper sitemap and ensures the homepage is included (valid download and output).
$web = new \Spekulatius\PHPScraper\PHPScraper;
// For the reference we are using a simple CSV and parse it. This matches the hosted CSV.
$csvString = "date,value\n1945-02-06,4.20\n1952-03-11,42";
$csvData = [['date', 'value'], ['1945-02-06', 4.20], ['1952-03-11', 42]];
// Case 1: Passing in an CSV string in.
$this->assertSame(
// Pass the CSV Data as reference in.
$csvData,
// Parse the $csvString directly.
(new \Spekulatius\PHPScraper\PHPScraper)
->parseCsv($csvString)
);
// Case 2: `go` + `parseCsv()`
$this->assertSame(
// Pass the CSV Data as reference in.
$csvData,
// Chained call using a CSV file as URL.
(new \Spekulatius\PHPScraper\PHPScraper)
->go('https://test-pages.phpscraper.de/test.csv')
->parseCsv()
);
// Case 3: `parseCsv()` with absolute URL.
$this->assertSame(
// Pass the CSV Data as reference in.
$csvData,
// Pass the absolutely URL to `parseCsv()`
(new \Spekulatius\PHPScraper\PHPScraper)
->parseCsv('https://test-pages.phpscraper.de/test.csv')
);
// Case 4: `go` + `parseCsv()` with relative URL.
$this->assertSame(
// Pass the CSV Data as reference in.
$csvData,
// The 'go' sets the base URL for the following relative path.
(new \Spekulatius\PHPScraper\PHPScraper)
->go('https://test-pages.phpscraper.de/meta/feeds.html')
->parseCsv('/test.csv')
);
// Case 5: `go` with base URL + `go` with relative URL + `parseCsv()`.
// 5.1. Ensure the final URL is correct.
$this->assertSame(
'https://test-pages.phpscraper.de/test.csv',
// The first 'go' sets the base URL for the following `go` with relative URL.
(new \Spekulatius\PHPScraper\PHPScraper)
->go('https://test-pages.phpscraper.de/meta/feeds.html')
->go('/test.csv')
->currentUrl()
);
// 5.2. Ensure the parsed CSV is correct.
$this->assertSame(
// Pass the CSV Data as reference in.
$csvData,
// The first 'go' sets the base URL for the following `go` with relative URL.
(new \Spekulatius\PHPScraper\PHPScraper)
->go('https://test-pages.phpscraper.de/meta/feeds.html')
->go('/test.csv')
->parseCsv()
);
// Case 6: With encoding params
$this->assertSame(
// Pass the CSV Data as reference in.
$csvData,
// The first 'go' sets the base URL for the following `go` with relative URL.
(new \Spekulatius\PHPScraper\PHPScraper)
->go('https://test-pages.phpscraper.de/meta/feeds.html')
->go('/test-custom.csv')
->parseCsv(null, '|', '"')
);
// Case 7: With encoding params and (relative) URL
$this->assertSame(
// Pass the CSV Data as reference in.
$csvData,
// The first 'go' sets the base URL for the following `go` with relative URL.
(new \Spekulatius\PHPScraper\PHPScraper)
->go('https://test-pages.phpscraper.de/meta/feeds.html')
->parseCsv('/test-custom.csv', '|', '"')
);
}
/**
* Check the pluming: Test the various ways to call `parseCsvWithHeader()`.
*
* @test
*/
public function testDifferentCsvWithHeaderCalls()
{
// Downloads the PHPScraper sitemap and ensures the homepage is included (valid download and output).
$web = new \Spekulatius\PHPScraper\PHPScraper;
// For the reference we are using a simple CSV and parse it. This matches the hosted CSV.
$csvString = "date,value\n1945-02-06,4.20\n1952-03-11,42";
$csvData = [
['date' => '1945-02-06', 'value' => 4.20],
['date' => '1952-03-11', 'value' => 42],
];
// Case 1: Passing in an CSV string in.
$this->assertSame(
// Pass the CSV Data as reference in.
$csvData,
// Parse the $csvString directly.
(new \Spekulatius\PHPScraper\PHPScraper)
->parseCsvWithHeader($csvString)
);
// Case 2: `parseCsvWithHeader()`
$this->assertSame(
// Pass the CSV Data as reference in.
$csvData,
// Chained call using a CSV file as URL.
(new \Spekulatius\PHPScraper\PHPScraper)
->parseCsvWithHeader('https://test-pages.phpscraper.de/test.csv')
);
// Case 2: `go` + `parseCsvWithHeader()`
$this->assertSame(
// Pass the CSV Data as reference in.
$csvData,
// Chained call using a CSV file as URL.
(new \Spekulatius\PHPScraper\PHPScraper)
->go('https://test-pages.phpscraper.de/test.csv')
->parseCsvWithHeader()
);
// Case 3: `parseCsvWithHeader()` with absolute URL.
$this->assertSame(
// Pass the CSV Data as reference in.
$csvData,
// Pass the absolutely URL to `parseCsvWithHeader()`
(new \Spekulatius\PHPScraper\PHPScraper)
->parseCsvWithHeader('https://test-pages.phpscraper.de/test.csv')
);
// Case 4: `go` + `parseCsvWithHeader()` with relative URL.
$this->assertSame(
// Pass the CSV Data as reference in.
$csvData,
// The 'go' sets the base URL for the following relative path.
(new \Spekulatius\PHPScraper\PHPScraper)
->go('https://test-pages.phpscraper.de/meta/feeds.html')
->parseCsvWithHeader('/test.csv')
);
// Case 5: `go` with base URL + `go` with relative URL + `parseCsvWithHeader()`.
// 5.1. Ensure the final URL is correct.
$this->assertSame(
'https://test-pages.phpscraper.de/test.csv',
// The first 'go' sets the base URL for the following `go` with relative URL.
(new \Spekulatius\PHPScraper\PHPScraper)
->go('https://test-pages.phpscraper.de/meta/feeds.html')
->go('/test.csv')
->currentUrl()
);
// 5.2. Ensure the parsed CSV is correct.
$this->assertSame(
// Pass the CSV Data as reference in.
$csvData,
// The first 'go' sets the base URL for the following `go` with relative URL.
(new \Spekulatius\PHPScraper\PHPScraper)
->go('https://test-pages.phpscraper.de/meta/feeds.html')
->go('/test.csv')
->parseCsvWithHeader()
);
// Case 6: With encoding params
$this->assertSame(
// Pass the CSV Data as reference in.
$csvData,
// The first 'go' sets the base URL for the following `go` with relative URL.
(new \Spekulatius\PHPScraper\PHPScraper)
->go('https://test-pages.phpscraper.de/meta/feeds.html')
->go('/test-custom.csv')
->parseCsvWithHeader(null, '|', '"')
);
// Case 7: With encoding params and (relative) URL
$this->assertSame(
// Pass the CSV Data as reference in.
$csvData,
// The first 'go' sets the base URL for the following `go` with relative URL.
(new \Spekulatius\PHPScraper\PHPScraper)
->go('https://test-pages.phpscraper.de/meta/feeds.html')
->parseCsvWithHeader('/test-custom.csv', '|', '"')
);
}
}

View file

@ -0,0 +1,108 @@
<?php
namespace Spekulatius\PHPScraper\Tests;
class ParserJsonTest extends \PHPUnit\Framework\TestCase
{
/**
* @test
*/
public function testJsonParsingContext()
{
$web = new \Spekulatius\PHPScraper\PHPScraper;
// This tests ensures an exception is thrown, if no context is given.
// Context means either it's been navigated before (URL context) or get something to (fetch +) parse
try {
$web = new \Spekulatius\PHPScraper\PHPScraper;
$web->parseJson();
} catch (\Exception $e) {
// Did we get the expected exception?
$this->assertSame(
'You can not call parseJson() without parameter or initial navigation.',
$e->getMessage()
);
}
}
/**
* Test the various ways to call `parseJson()`.
*
* @test
*/
public function testDifferentJsonCalls()
{
// Downloads the PHPScraper sitemap and ensures the homepage is included (valid download and output).
$web = new \Spekulatius\PHPScraper\PHPScraper;
// For the reference we are using a simple JSON and parse it.
$jsonString = $web->fetchAsset('https://test-pages.phpscraper.de/index.json');
$jsonData = json_decode($jsonString, true);
// Case 1: Passing in an JSON string in.
$this->assertSame(
// Pass the JSON Data as reference in.
$jsonData,
// Parse the $jsonString directly.
(new \Spekulatius\PHPScraper\PHPScraper)
->parseJson($jsonString)
);
// Case 2: `go` + `parseJson()`
$this->assertSame(
// Pass the JSON Data as reference in.
$jsonData,
// Chained call using a JSON file as URL.
(new \Spekulatius\PHPScraper\PHPScraper)
->go('https://test-pages.phpscraper.de/index.json')
->parseJson()
);
// Case 3: `parseJson()` with absolute URL.
$this->assertSame(
// Pass the JSON Data as reference in.
$jsonData,
// Pass the absolutely URL to `parseJson()`
(new \Spekulatius\PHPScraper\PHPScraper)
->parseJson('https://test-pages.phpscraper.de/index.json')
);
// Case 4: `go` + `parseJson()` with relative URL.
$this->assertSame(
// Pass the JSON Data as reference in.
$jsonData,
// The 'go' sets the base URL for the following relative path.
(new \Spekulatius\PHPScraper\PHPScraper)
->go('https://test-pages.phpscraper.de/meta/feeds.html')
->parseJson('/index.json')
);
// Case 5: `go` with base URL + `go` with relative URL + `parseJson()`.
// 5.1. Ensure the final URL is correct.
$this->assertSame(
'https://test-pages.phpscraper.de/index.json',
// The first 'go' sets the base URL for the following `go` with relative URL.
(new \Spekulatius\PHPScraper\PHPScraper)
->go('https://test-pages.phpscraper.de/meta/feeds.html')
->go('/index.json')
->currentUrl()
);
// 5.2. Ensure the parsed JSON is correct.
$this->assertSame(
// Pass the JSON Data as reference in.
$jsonData,
// The first 'go' sets the base URL for the following `go` with relative URL.
(new \Spekulatius\PHPScraper\PHPScraper)
->go('https://test-pages.phpscraper.de/meta/feeds.html')
->go('/index.json')
->parseJson()
);
}
}

View file

@ -0,0 +1,107 @@
<?php
namespace Spekulatius\PHPScraper\Tests;
class ParserXmlTest extends \PHPUnit\Framework\TestCase
{
/**
* @test
*/
public function testJsonParsingContext()
{
$web = new \Spekulatius\PHPScraper\PHPScraper;
// This tests ensures an exception is thrown, if no context is given.
// Context means either it's been navigated before (URL context) or get something to (fetch +) parse
try {
$web = new \Spekulatius\PHPScraper\PHPScraper;
$web->parseXml();
} catch (\Exception $e) {
// Did we get the expected exception?
$this->assertSame(
'You can not call parseXml() without parameter or initial navigation.',
$e->getMessage()
);
}
}
/**
* @test
*/
public function testDifferentXmlCalls()
{
// Downloads the PHPScraper sitemap and ensures the homepage is included (valid download and output).
$web = new \Spekulatius\PHPScraper\PHPScraper;
// For the reference we are using a simple XML and parse it.
$xmlString = $web->fetchAsset('https://test-pages.phpscraper.de/sitemap.xml');
$xml = simplexml_load_string($xmlString, 'SimpleXMLElement', LIBXML_NOCDATA);
$xmlData = json_decode((string) json_encode($xml), true);
// Case 1: Passing in an XML string in.
$this->assertSame(
// Pass the XML Data as reference in.
$xmlData,
// Parse the XML string directly.
(new \Spekulatius\PHPScraper\PHPScraper)
->parseXml($xmlString)
);
// Case 2: `go` + `parseXml()`
$this->assertSame(
// Pass the XML Data as reference in.
$xmlData,
// Chained call with XML as URL
(new \Spekulatius\PHPScraper\PHPScraper)
->go('https://test-pages.phpscraper.de/sitemap.xml')
->parseXml()
);
// Case 3: `parseXml()` with absolute URL.
$this->assertSame(
// Pass the XML Data as reference in.
$xmlData,
// Pass the absolutely URL to `parseXml()`
(new \Spekulatius\PHPScraper\PHPScraper)
->parseXml('https://test-pages.phpscraper.de/sitemap.xml')
);
// Case 4: `go` + `parseXml()` with relative URL.
$this->assertSame(
// Pass the XML Data as reference in.
$xmlData,
// The 'go' sets the base URL for the following relative path.
(new \Spekulatius\PHPScraper\PHPScraper)
->go('https://test-pages.phpscraper.de/meta/feeds.html')
->parseXml('/sitemap.xml')
);
// Case 5: `go` with base URL + `go` with relative URL + `parseXml()`.
// 5.1. Ensure the final URL is correct.
$this->assertSame(
'https://test-pages.phpscraper.de/sitemap.xml',
// The first 'go' sets the base URL for the following `go` with relative URL.
(new \Spekulatius\PHPScraper\PHPScraper)
->go('https://test-pages.phpscraper.de/meta/feeds.html')
->go('/sitemap.xml')
->currentUrl()
);
// 5.2. Ensure the parsed JSON is correct.
$this->assertSame(
// Pass the XML Data as reference in.
$xmlData,
// The first 'go' sets the base URL for the following `go` with relative URL.
(new \Spekulatius\PHPScraper\PHPScraper)
->go('https://test-pages.phpscraper.de/meta/feeds.html')
->go('/sitemap.xml')
->parseXml()
);
}
}

View file

@ -0,0 +1,48 @@
<?php
namespace Spekulatius\PHPScraper\Tests;
class RedirectTest extends \PHPUnit\Framework\TestCase
{
/**
* @test
*/
public function testRedirect()
{
$web = new \Spekulatius\PHPScraper\PHPScraper;
// Navigate to the test page: This redirects to phpscraper.de
$web->go('https://test-pages.phpscraper.de');
$this->assertNotSame(
$web->currentUrl,
'https://test-pages.phpscraper.de/'
);
$this->assertSame(
$web->currentUrl,
'https://phpscraper.de/'
);
}
/**
* @test
*/
public function testDisabledRedirect()
{
$web = new \Spekulatius\PHPScraper\PHPScraper;
$web->setConfig([
'follow_redirects' => false,
'follow_meta_refresh' => false,
'max_redirects' => -1,
]);
// Navigate to the test page: This redirects to phpscraper.de
$web->go('https://test-pages.phpscraper.de');
$this->assertSame(
'https://test-pages.phpscraper.de',
$web->currentUrl,
);
}
}

105
lib/sc/tests/TitleTest.php Normal file
View file

@ -0,0 +1,105 @@
<?php
namespace Spekulatius\PHPScraper\Tests;
class TitleTest extends \PHPUnit\Framework\TestCase
{
/**
* @test
*/
public function testMissingTitle()
{
$web = new \Spekulatius\PHPScraper\PHPScraper;
// Navigate to the test page.
$web->go('https://test-pages.phpscraper.de/meta/missing.html');
// Check the title as not given (null)
$this->assertNull($web->title);
}
/**
* @test
*/
public function testWithHTMLEntity()
{
$web = new \Spekulatius\PHPScraper\PHPScraper;
// Navigate to the test page.
$web->go('https://test-pages.phpscraper.de/meta/html-entities.html');
// Check the title
$this->assertSame(
'Cat & Mouse',
$web->title
);
}
/**
* @test
*/
public function testLoremIpsum()
{
$web = new \Spekulatius\PHPScraper\PHPScraper;
// Navigate to the test page.
$web->go('https://test-pages.phpscraper.de/meta/lorem-ipsum.html');
// Check the title
$this->assertSame(
'Lorem Ipsum',
$web->title
);
}
/**
* @test
*/
public function testGermanUmlaute()
{
$web = new \Spekulatius\PHPScraper\PHPScraper;
// Navigate to the test page.
$web->go('https://test-pages.phpscraper.de/meta/german-umlaute.html');
// Check the title
$this->assertSame(
'A page with plenty of German umlaute everywhere (ä ü ö)',
$web->title
);
}
/**
* @test
*/
public function testChineseCharacters()
{
$web = new \Spekulatius\PHPScraper\PHPScraper;
// Navigate to the test page.
$web->go('https://test-pages.phpscraper.de/meta/chinese-characters.html');
// Check the title
$this->assertSame(
'Page with Chinese Characters all over the place (加油)',
$web->title
);
}
/**
* @test
*/
public function testLongTitle()
{
$web = new \Spekulatius\PHPScraper\PHPScraper;
// Navigate to the test page.
$web->go('https://test-pages.phpscraper.de/title/long-title.html');
// Check the title
$this->assertSame(
'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed mollis purus id ex consectetur facilisis. In gravida sodales nisl a consequat. Aenean ipsum sem, congue et rhoncus a, feugiat eget enim. Duis ut malesuada neque. Nam justo est, interdum eu massa in, volutpat vestibulum libero. Mauris a varius mauris, in vulputate ligula. Nulla rhoncus eget purus a sodales. Nulla facilisi. Proin purus purus, sodales non dolor in, lobortis elementum augue. Nulla sagittis, ex eu placerat varius, nulla mi rutrum odio, sit amet lacinia ipsum urna nec massa. Quisque posuere mauris id condimentum viverra.',
$web->title
);
}
}

View file

@ -0,0 +1,48 @@
<?php
namespace Spekulatius\PHPScraper\Tests;
class TwitterCardTest extends \PHPUnit\Framework\TestCase
{
/**
* @test
*/
public function testMissingTwitterCard()
{
$web = new \Spekulatius\PHPScraper\PHPScraper;
// Go to the test page
$web->go('https://test-pages.phpscraper.de/meta/missing.html');
// Empty array, because there aren't any twitter cards props set.
$this->assertTrue(is_iterable($web->twitterCard));
$this->assertTrue(empty($web->twitterCard));
}
/**
* @test
*/
public function testTwitterCard()
{
$web = new \Spekulatius\PHPScraper\PHPScraper;
// Navigate to the test page.
$web->go('https://test-pages.phpscraper.de/twittercard/example.html');
// Check elements
$this->assertSame('summary_large_image', $web->twitterCard['twitter:card']);
$this->assertSame('Lorem Ipsum', $web->twitterCard['twitter:title']);
// The whole set.
$this->assertSame(
[
'twitter:card' => 'summary_large_image',
'twitter:title' => 'Lorem Ipsum',
'twitter:description' => 'Lorem ipsum dolor etc.',
'twitter:url' => 'https://test-pages.phpscraper.de/meta/lorem-ipsum.html',
'twitter:image' => 'https://test-pages.phpscraper.de/assets/cat.jpg',
],
$web->twitterCard
);
}
}

212
lib/sc/tests/UrlTest.php Normal file
View file

@ -0,0 +1,212 @@
<?php
namespace Spekulatius\PHPScraper\Tests;
/**
* Ensure our URL lib, https://github.com/thephpleague/uri, is integrated correctly and works as expected.
*/
class UrlTest extends \PHPUnit\Framework\TestCase
{
/**
* If null is passed to `makeUrlAbsolute`, it should always return null.
*
* @test
*/
public function testNullPassingThrough()
{
$web = new \Spekulatius\PHPScraper\PHPScraper;
$this->assertNull($web->makeUrlAbsolute(null));
}
/**
* @test
*/
public function validateUriTest()
{
$web = new \Spekulatius\PHPScraper\PHPScraper;
// We use any URL for this.
$web->go('https://test-pages.phpscraper.de/content/lists.html');
// Ensure the URL is set correctly.
$this->assertSame(
'https://test-pages.phpscraper.de/content/lists.html',
$web->currentUrl
);
// Ensure the host is parsed correctly.
$this->assertSame(
'test-pages.phpscraper.de',
$web->currentHost
);
// Ensure the host with protocol is parsed correctly.
$this->assertSame(
'https://test-pages.phpscraper.de',
$web->currentBaseHost
);
}
/**
* @test
*/
public function testCurrentBaseHostWithBase()
{
$web = new \Spekulatius\PHPScraper\PHPScraper;
// Navigate to the test page.
// Contains: <base href="https://test-pages-with-base-href.phpscraper.de/">
$web->go('https://test-pages.phpscraper.de/meta/image/absolute-path-with-base-href.html');
// Check the base href being passed through the current base host.
$this->assertSame(
'https://test-pages-with-base-href.phpscraper.de',
$web->currentBaseHost
);
}
/**
* Basic processing of the URLs.
*
* @test
*/
public function testMakeUrlAbsolute()
{
$web = new \Spekulatius\PHPScraper\PHPScraper;
// Navigate to test page: This sets the base URL.
$web->go('https://phpscraper.de');
// Test variations of paths to be processed
// With leading slash
$this->assertSame(
'https://phpscraper.de/index.html',
$web->makeUrlAbsolute('/index.html'),
);
// Without leading slash
$this->assertSame(
'https://phpscraper.de/index.html',
$web->makeUrlAbsolute('index.html'),
);
// Paths are considered.
$this->assertSame(
'https://phpscraper.de/test/index.html',
$web->makeUrlAbsolute('test/index.html'),
);
// Absolutely URLs are untouched.
$this->assertSame(
'https://example.com/index.html',
$web->makeUrlAbsolute('https://example.com/index.html'),
);
// Protocol is considered
$this->assertSame(
'http://example.com/index.html',
$web->makeUrlAbsolute('http://example.com/index.html'),
);
}
/**
* Basic processing of the URLs.
*
* @test
*/
public function testMakeUrlAbsoluteConsiderBaseHref()
{
$web = new \Spekulatius\PHPScraper\PHPScraper;
/**
* Navigate to test page: This sets the base URL.
*
* It contains:
*
* ```html
* <base href="https://test-pages-with-base-href.phpscraper.de/">
* ```
*
* While it's located on `test-pages.phpscraper.de`.
*
* This page isn't actually used. It's purely to set the context.
*/
$web->go('https://test-pages.phpscraper.de/meta/image/absolute-path-with-base-href.html');
// Test variations of paths to be processed
// With leading slash
$this->assertSame(
'https://test-pages-with-base-href.phpscraper.de/index.html',
$web->makeUrlAbsolute('/index.html'),
);
// Without leading slash
$this->assertSame(
'https://test-pages-with-base-href.phpscraper.de/index.html',
$web->makeUrlAbsolute('index.html'),
);
// Paths are considered.
$this->assertSame(
'https://test-pages-with-base-href.phpscraper.de/test/index.html',
$web->makeUrlAbsolute('test/index.html'),
);
// Absolutely URLs are untouched.
$this->assertSame(
'https://example.com/index.html',
$web->makeUrlAbsolute('https://example.com/index.html'),
);
// Protocol is considered
$this->assertSame(
'http://example.com/index.html',
$web->makeUrlAbsolute('http://example.com/index.html'),
);
}
/**
* Test if passed in hosts are considered. It trumps any base-href and current url.
*
* @test
*/
public function testMakeUrlAbsoluteWithBaseHost()
{
$web = new \Spekulatius\PHPScraper\PHPScraper;
// Navigate to test page: This sets the base URL.
$web->go('https://phpscraper.de');
// Test variations of paths to be processed
// With leading slash
$this->assertSame(
'https://example.com/index.html',
$web->makeUrlAbsolute('/index.html', 'https://example.com'),
);
// Without leading slash
$this->assertSame(
'https://example.com/index.html',
$web->makeUrlAbsolute('index.html', 'https://example.com'),
);
// Paths are considered.
$this->assertSame(
'https://example.com/test/index.html',
$web->makeUrlAbsolute('test/index.html', 'https://example.com'),
);
// Absolutely URLs are untouched.
$this->assertSame(
'https://example.com/index.html',
$web->makeUrlAbsolute('https://example.com/index.html', 'https://example-2.com/test/with/path'),
);
// Protocol is considered
$this->assertSame(
'http://example.com/index.html',
$web->makeUrlAbsolute('http://example.com/index.html', 'https://example-2.com/test/with/path'),
);
}
}