非框架项目需手动 require vendor/autoload.php;多次调用 setConfig 会与默认值合并,未重复的旧配置会被重置;setConfig 的 timeout 设为 0 会禁用超时
PHPScraper
spekulatiusGPL-3.0活跃维护PHP 版网页抓取工具,提供类似 BeautifulSoup 的简洁 API,可解析 HTML、提取页面数据,并支持无头浏览器渲染动态页面。
A universal web-util for PHP.
composer require spekulatius/phpscraperREADME 未说明,纯 PHP 库,无 GPU 或显存要求
PHP 网页抓取工具库,省去选择器和数据结构整理,直接取标题、链接、元数据
PHP 版网页抓取工具,提供类似 BeautifulSoup 的简洁 API,可解析 HTML、提取页面数据,并支持无头浏览器渲染动态页面。
核心能力
- 用属性或方法两种方式调用抓取结果,如 $web->title
- 内置 meta、社交标签、标题、正文、图片、链接等提取器
- linksWithDetails 返回链接的 rel、nofollow、图片等明细
- fetchAsset 下载文件,支持绝对与相对 URL
- parseJson/parseXml/parseCsv 解析字符串或 URL,含表头模式
容易踩的坑
- 3.0.0最新正式版2024-07-19 · 2024-07-19 19:49 UTC
What's Changed
- Fix typos and a critical error by @szepeviktor in https://github.com/spekulatius/PHPScraper/pull/190
- Fix few problems reported by PHPStan by @szepeviktor in https://github.com/spekulatius/PHPScraper/pull/192
- Add Pint by @szepeviktor in https://github.com/spekulatius/PHPScraper/pull/195
- Fix HTTPClient config by @szepeviktor in https://github.com/spekulatius/PHPScraper/pull/194
- Upgrading repo tools by @spekulatius in https://github.com/spekulatius/PHPScraper/pull/196
- Upgrade from league/uri 6.x to league/uri 7.x, replacing deprecated function use with new recommended ones by @scotteuser in https://github.com/spekulatius/PHPScraper/pull/200
- Pint by @spekulatius in https://github.com/spekulatius/PHPScraper/pull/201
- Add CI job names by @szepeviktor in https://github.com/spekulatius/PHPScraper/pull/199
- Upgrading Symfony dependencies to allow ^7.0 by @tentacode in https://github.com/spekulatius/PHPScraper/pull/204
New Contributors
- @szepeviktor made their first contribution in https://github.com/spekulatius/PHPScraper/pull/190
- @scotteuser made their first contribution in https://github.com/spekulatius/PHPScraper/pull/200
- @tentacode made their first contribution in https://github.com/spekulatius/PHPScraper/pull/204
Full Changelog: https://github.com/spekulatius/PHPScraper/compare/2.0.0...3.0.0
- 2.0.0v2.0.0: Service Update2023-06-18 · 2023-06-18 22:28 UTC
查看更新说明
v2 implements changes required due to Goutte being archived. See UPGRADING.md
What's Changed
- Adding extraction by @spekulatius in https://github.com/spekulatius/PHPScraper/pull/169
- Various PHPStan improvements by @spekulatius in https://github.com/spekulatius/PHPScraper/pull/171
- Chore: Fix readme example by @spekulatius in https://github.com/spekulatius/PHPScraper/pull/173
- Fixing local runs of phpunit by adding "bootstrap" by @spekulatius in https://github.com/spekulatius/PHPScraper/pull/174
- Drop PHP 7.3 and 7.4 (fixes #180) by @spekulatius in https://github.com/spekulatius/PHPScraper/pull/182
- Adding PHP 8.3 to testing pipeline by @spekulatius in https://github.com/spekulatius/PHPScraper/pull/185
- Switch from Goutte to BrowserKit (fixes #181) by @spekulatius in https://github.com/spekulatius/PHPScraper/pull/183
- added phpstan in github actions by @nadar in https://github.com/spekulatius/PHPScraper/pull/184
- Move phpstan to local temp path to ensure Windows users can run it by @spekulatius in https://github.com/spekulatius/PHPScraper/pull/188
- Fix and Improve Tests by @spekulatius in https://github.com/spekulatius/PHPScraper/pull/186
- v2 by @spekulatius in https://github.com/spekulatius/PHPScraper/pull/187
New Contributors
- @nadar made their first contribution in https://github.com/spekulatius/PHPScraper/pull/184
Full Changelog: https://github.com/spekulatius/PHPScraper/compare/1.0.2...2.0.0
- 1.0.0v1.0.0: Finally Stable!2022-11-23 · 2022-11-23 23:30 UTC
查看更新说明
It's been a while until PHPScraper reached
v1. But now it's here! This first stable release covers:- More rounded parsing and consistent naming
- Improved documentation website in multiple languages
- Better Testing and Test coverage
- Parsing of Feeds
sitemap.xml, RSS feeds and static search indexes - Parsing of plaintext files such as CSV, XML and JSON
You can find all major commits in the changelog. Please check the upgrade instructions to get to v1.
Special thanks to all contributors: @walirazzaq, @nadar, @nathabonfim59, @datlechin, @tacman, @fumiya5863 and @vitormattos! :tada:
用户点评
登录用户的真实使用记录,可按版本和硬件筛选还没有人点评。第一个说出真实体验的人最有价值。
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 (formerly Goutte) to access the web
- League/URI to process URLs
- donatello-za/rake-php-plus to extract and analyze keywords
See 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.
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:
// 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:
$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 and other
<head>-information - Social-Media information like Twitter Card and Facebook Open Graph
- Content: Headings, Outline, Texts and Lists
- Images
- Links
- Keywords
A full list of methods with example code can be found on phpscraper.de. Further examples are in the tests.
Download Files
Besides processing the content on the page itself, you can download files using fetchAsset:
// 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. 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:
(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:
parseJsonparseXmlparseCsvparseCsvWithHeader(generates an asso. array using the first row)
Each method can process both strings as well as URLs:
// 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 and in the tests.
Check the playground.php if you prefer learning by doing. You get it up and running with:
$ git clone [email protected]:spekulatius/PHPScraper.git && composer update
:muscle: Roadmap
The future development is organized into milestones. Releases follow semver.
v1: Building the first stable version
- 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. Goutte has been archived.
v3: Expand the functionality and cover more 'types'
- 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
TBC.
:heart_eyes: Sponsors
PHPScraper is sponsored by:
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 or donation. 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:
$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:
$web->setConfig(['proxy' => 'http://user:[email protected]:3128']);
Timeout
You can set the timeout using setConfig:
$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:
$web->setConfig(['disable_ssl' => true]);
You can call setConfig multiple times. Each call merges the given config with the defaults again, not with the config from a previous call — so any custom values from an earlier call that you don't repeat will be reset to their defaults.
:rocket: Installation with Composer
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
require __DIR__ . '/vendor/autoload.php';
// ...
Now you can now use any of the examples on the documentation website or from the tests/-folder.
Please consider supporting PHPScraper with a star or sponsorship:
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:
composer test
You can find the tests here. The test pages are publicly available.