PHP Scraper - PHP용 웹 스크래퍼 라이브러리
본문
PHP 용 웹 액세스 라이브러리
PHP에서 웹에 액세스하는 것이 더 쉽습니다. 이것은 훌륭한 라이브러리를 둘러싼 독단적 래퍼입니다.
예제는 이야기를 훨씬 더 잘 전달합니다. 보세요!
아이디어 ?️
웹 사이트에 액세스하고 웹의 기본 정보를 수집하는 것은 너무 복잡합니다. Goutte 주변에 있는 이 포장지 (새 창에서 열림)는 더 쉽게 만듭니다. XPath 및 co.에서 귀하를 저장하여 필요한 모든 것에 직접 액세스 할 수 있습니다.
Examples
다음은 이 시점에서 라이브러리가 수행 할 수 있는 작업의 몇 가지 예입니다.
스크랩 메타 정보 :
$web = new \spekulatius\phpscraper();
/**
* Navigate to the test page. It contains:
*
* <meta name="author" content="Lorem ipsum" />
* <meta name="keywords" content="Lorem,ipsum,dolor" />
* <meta name="description" content="Lorem ipsum dolor etc." />
* <meta name="image" content="https://test-pages.phpscraper.de/assets/cat.jpg" />
*/
$web->go('https://test-pages.phpscraper.de/meta/lorem-ipsum.html');
// Get the information:
echo $web->author; // "Lorem ipsum"
echo $web->description; // "Lorem ipsum dolor etc."
echo $web->image; // "https://test-pages.phpscraper.de/assets/cat.jpg"
대부분의 다른 정보는 문자열 또는 배열로 직접 액세스 할 수 있습니다.
이미지와 같은 콘텐츠 스크랩 :
$web = new \spekulatius\phpscraper();
/**
* Navigate to the test page. This page contains two images:
*
* <img src="https://test-pages.phpscraper.de/assets/cat.jpg" alt="absolute path">
* <img src="/assets/cat.jpg" alt="relative path">
*/
$web->go('https://test-pages.phpscraper.de/meta/lorem-ipsum.html');
var_dump($web->imagesWithDetails);
/**
* [
* '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->images를 사용하여 간단한 이미지 목록을 사용할 수도 있습니다.
더 많은 예제 코드는 사이드 바 또는 테스트에서 찾을 수 있습니다.
설치
평소와 같이 composer를 통해 수행됩니다.
composer require spekulatius/phpscraper
이렇게 하면 패키지가 자동으로 로드 됩니다. 이제 위에서 언급 한 예를 사용할 수 있습니다.
Basics
설치
라이브러리는 일반적으로 composer를 사용하여 설치됩니다.
composer require spekulatius/phpscraper
용법
설치가 완료되면 Composer 자동 로더가 패키지를 선택합니다. VanillaPHP 라이브러리를 사용하는 경우 스크립트에 자동 로더를 포함해야 합니다.
require 'vendor/autoload.php';
Laravel, SilverStripe 또는 Flarum과 같은 프레임 워크를 사용하는 경우 이 단계가 필요하지 않습니다.
Header
웹 사이트 제목 스크랩
웹 사이트에서 제목을 긁어내는 것은 간단합니다. 다음 예제는 PHPScraper를 사용하여 작동하는 방법을 보여줍니다.
간단한 예
웹 사이트 제목을 긁어내는 방법에 대한 아주 간단한 예 :
$web = new \spekulatius\phpscraper();
// Navigate to the test page - this one doesn't contain a title-tag.
$web->go('https://test-pages.phpscraper.de/meta/lorem-ipsum.html');
/**
* Contains:
*
* <title>Lorem Ipsum</title>
*/
// Fetch the title. This should return:
// "Lorem Ipsum"
var_dump($web->title);
누락 된 제목
제목이 누락 된 경우 null이 반환됩니다.
$web = new \spekulatius\phpscraper();
// Navigate to the test page - this one doesn't contain a title-tag.
$web->go('https://test-pages.phpscraper.de/meta/missing.html');
// Fetch the title. This should return null.
var_dump($web->title);
참고 : 이것이 기본 동작입니다. 소스 HTML에 태그가 없어서 태그를 찾을 수 없는 경우 null이 반환됩니다. 반복 가능한 항목이 비어있는 경우 (예 : 이미지가 없는 페이지에서 이미지 스크랩) 빈 배열이 반환됩니다.
특수 문자
German Umlaute로 웹 사이트 제목 로드
$web = new \spekulatius\phpscraper();
/**
* Navigate to the test page. It contains:
*
* <title>A page with plenty of German umlaute everywhere (ä ü ö)</title>
*/
$web->go('https://test-pages.phpscraper.de/meta/german-umlaute.html');
// Print the title: "A page with plenty of German umlaute everywhere (ä ü ö)"
echo $web->title;
UTF-8 문자와 유사한 방식으로 작동해야 합니다.
HTML 엔티티
HTML 엔터티를 확인해야 합니다.
$web = new \spekulatius\phpscraper();
/**
* Navigate to the test page. Contains:
*
* <title>Cat & Mouse</title>
*/
$web->go('https://test-pages.phpscraper.de/meta/html-entities.html');
// Print the title: "Cat & Mouse'"
echo $web->title;
엔티티와 특수 문자는 라이브러리 전체에서 고려되었습니다. 예상대로 작동하지 않는 곳을 찾으면 문제를 제기하십시오.
Scrape Header Tags
헤더 태그에는 종종 웹 페이지에 대한 유용한 정보와 해당 페이지가 속한 웹 사이트의 전체 구조에 어떻게 맞는지에 대한 정보가 포함됩니다. 다음 예는 <head> 및 이들 주변의 컬렉션에서 특정 정보에 액세스 하는 방법을 보여줍니다.
Charset
정의 된 문자 집합에 액세스하려면 다음 방법을 사용할 수 있습니다.
$web = new \spekulatius\phpscraper();
/**
* Navigate to the test page. It contains:
*
* <meta charset="utf-8" />
*/
$web->go('https://test-pages.phpscraper.de/meta/lorem-ipsum.html');
// Print the contentType
echo $web->charset; // "utf-8"
Viewport
뷰포트 및 메타 키워드와 같은 일부 경우 문자열은 배열을 나타내며 다음과 같이 제공됩니다.
$web = new \spekulatius\phpscraper();
/**
* Navigate to the test page. It contains:
*
* <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no, maximum-scale=1, user-scalable=no" />
*/
$web->go('https://test-pages.phpscraper.de/meta/lorem-ipsum.html');
/**
* Get the viewport as an array. It should contain:
*
* [
* 'width=device-width',
* 'initial-scale=1',
* 'shrink-to-fit=no',
* 'maximum-scale=1',
* 'user-scalable=no'
* ],
*/
var_dump($web->viewport);
원래 문자열에 액세스 해야 하는 경우 원래 문자열에도 액세스합니다.
$web = new \spekulatius\phpscraper();
$web->go('https://test-pages.phpscraper.de/meta/lorem-ipsum.html');
/**
* Get the viewport as a string. Prints:
*
* "width=device-width, initial-scale=1, shrink-to-fit=no, maximum-scale=1, user-scalable=no"
*/
echo $web->viewportString;
Canonical URL
표준 URL (주어진 경우)은 아래 예와 같이 액세스 할 수 있습니다.
$web = new \spekulatius\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');
// Print the canonical URL
echo $web->canonical; // "https://test-pages.phpscraper.de/navigation/2.html"
표준 링크가 설정되지 않은 경우 메서드는 null을 반환합니다.
Content Type
콘텐츠 유형에 액세스하려면 다음 기능을 사용할 수 있습니다.
$web = new \spekulatius\phpscraper();
/**
* Navigate to the test page. It contains:
*
* <meta http-equiv="Content-type" content="text/html; charset=utf-8" />
*/
$web->go('https://test-pages.phpscraper.de/meta/lorem-ipsum.html');
// Print the contentType
echo $web->contentType; // "text/html; charset=utf-8"
CSFR Token
CSFR 토큰 방법은 토큰이 "csrf-token"이라는 이름의 메타 태그에 저장되어 있다고 가정합니다. 이것이 Laravel의 기본값입니다. 다음 코드를 사용하여 액세스 할 수 있습니다.
$web = new \spekulatius\phpscraper();
/**
* Navigate to the test page. It contains:
*
* <meta name="csrf-token" content="token" />
*/
$web->go('https://test-pages.phpscraper.de/meta/lorem-ipsum.html');
// Get the csrfToken
echo $web->csrfToken; // "token"
Combined Header Tags
위에서 언급 한 모든 방법에 액세스하려면 headers-method를 사용하십시오. 다음과 같이 정의됩니다.
/**
* get the header collected as an array
*
* @return array
*/
public function headers()
{
return [
'charset' => $this->charset(),
'contentType' => $this->contentType(),
'viewport' => $this->viewport(),
'canonical' => $this->canonical(),
'csrfToken' => $this->csrfToken(),
];
}
메타 태그 액세스에 대한 추가 정보.
Scraping Meta Tags
메타 정보에 액세스하는 것은 이전에 표시된 헤더 태그와 유사한 패턴을 따릅니다. 다음은 몇 가지 예입니다.
Meta Author, Description and Image
다음 예는 세 가지 속성의 추출을 보여줍니다.
- the Meta Author,
- the Meta Description and
- the Meta Image URL
$web = new \spekulatius\phpscraper();
/**
* Navigate to the test page. It contains:
*
* <meta name="author" content="Lorem ipsum" />
* <meta name="keywords" content="Lorem,ipsum,dolor" />
* <meta name="description" content="Lorem ipsum dolor etc." />
* <meta name="image" content="https://test-pages.phpscraper.de/assets/cat.jpg" />
*/
$web->go('https://test-pages.phpscraper.de/meta/lorem-ipsum.html');
// Get the information:
echo $web->author; // "Lorem ipsum"
echo $web->description; // "Lorem ipsum dolor etc."
echo $web->image; // "https://test-pages.phpscraper.de/assets/cat.jpg"
Meta Keywords
키워드 메타 태그는 당연히 배열이며 사용자의 편의를 위해 분할 됩니다.
$web = new \spekulatius\phpscraper();
/**
* Navigate to the test page. It contains:
*
* <meta name="keywords" content="one, two, three">
*/
$web->go('https://test-pages.phpscraper.de/meta/keywords/parse-spaces.html');
// dump the keywords as an array
var_dump($web->keywords); // ['one', 'two', 'three']
또는 원래 키워드 문자열에 액세스 할 수 있습니다.
$web = new \spekulatius\phpscraper();
$web->go('https://test-pages.phpscraper.de/meta/keywords/parse-spaces.html');
// Print the keywords as string
echo $web->keywordString; // "one, two, three"
이것은 "키워드"메타 태그의 키워드만을 나타냅니다. PHPScraper를 사용하여 콘텐츠 키워드를 추출 할 수도 있습니다.
Combined Meta Tags
모든 메타 속성에 액세스하려면 metaTags 메서드를 사용할 수 있습니다. 위에서 언급 한 메서드를 배열로 반환합니다. 다음과 같이 정의됩니다.
/**
* get the meta collected as an array
*
* @return array
*/
public function metaTags()
{
return [
'author' => $this->author(),
'image' => $this->image(),
'keywords' => $this->keywords(),
'description' => $this->description(),
];
}
위의 예에서 다음과 같이 사용됩니다.
$web = new \spekulatius\phpscraper();
$web->go('https://test-pages.phpscraper.de/meta/keywords/parse-spaces.html');
var_dump($web->metaTags);
/**
* Contains:
*
* [
* 'Lorem ipsum',
* 'https://test-pages.phpscraper.de/assets/cat.jpg',
* ['one', 'two', 'three'],
* 'Lorem ipsum dolor etc.',
* ]
*/
Missing Meta Tags
다른 메타 속성에 액세스 해야 하는 경우 패키지에 기여하거나 GitHub에 문제를 제출하는 것을 고려할 수 있습니다 (새 창에서 열림).
Scraping Social Media Meta Tags
웹 사이트에서 소셜 미디어 공유 태그를 스크래핑 하는 방법은 다음과 같습니다. 정확한 결과 세트는 제공된 태그에 따라 다릅니다. 접두사가 붙은 네임 스페이스 (예 : Twitter : Twitter 카드 용)에 있는 한 모든 태그가 포함됩니다.
Open-Graph (OG) Data
오픈 그래프 데이터를 가져올 수 있습니다.
$web = new \spekulatius\phpscraper();
/**
* Navigate to the test page. Page contains:
*
* <!-- open graph example -->
* <meta property="og:site_name" content="Lorem ipsum" />
* <meta property="og:type" content="website" />
* <meta property="og:title" content="Lorem Ipsum" />
* <meta property="og:description" content="Lorem ipsum dolor etc." />
* <meta property="og:url" content="https://test-pages.phpscraper.de/lorem-ipsum.html" />
* <meta property="og:image" content="https://test-pages.phpscraper.de/assets/cat.jpg" />
*
* @see https://test-pages.phpscraper.de/og/example.html
*/
$web->go('https://test-pages.phpscraper.de/og/example.html');
// Should print 'Lorem Ipsum'
echo $web->openGraph['og:title'];
// Should print 'Lorem ipsum dolor etc.'
echo $web->openGraph['og:description'];
// the whole set:
$data = $web->openGraph;
/**
* $data now contains:
*
* [
* '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/lorem-ipsum.html',
* 'og:image' => 'https://test-pages.phpscraper.de/assets/cat.jpg',
* ]
*/
데이터가 발견되지 않으면 배열이 비어있는 상태로 반환 됩니다. #Twitter 카드
Twitter Card
Twitter 카드 구문 분석은 유사하게 작동합니다.
$web = new \spekulatius\phpscraper();
/**
* Navigate to the test page. The page contains the following Twitter Card:
*
* <!-- Twitter card -->
* <meta name="twitter:card" content="summary_large_image" />
* <meta name="twitter:title" content="Lorem Ipsum" />
* <meta name="twitter:description" content="Lorem ipsum dolor etc." />
* <meta name="twitter:url" content="https://test-pages.phpscraper.de/lorem-ipsum.html" />
* <meta name="twitter:image" content="https://test-pages.phpscraper.de/assets/cat.jpg" />
*
* @see https://test-pages.phpscraper.de/twittercard/example.html
*/
$web->go('https://test-pages.phpscraper.de/twittercard/example.html');
// Should print out 'summary_large_image'
echo $web->twitterCard['twitter:card']);
// Should print out 'Lorem Ipsum'
echo $web->twitterCard['twitter:title']);
// The whole set.
$data = $web->twitterCard;
/**
* $data contains now:
*
* [
* 'twitter:card' => 'summary_large_image',
* 'twitter:title' => 'Lorem Ipsum',
* 'twitter:description' => 'Lorem ipsum dolor etc.',
* 'twitter:url' => 'https://test-pages.phpscraper.de/lorem-ipsum.html',
* 'twitter:image' => 'https://test-pages.phpscraper.de/assets/cat.jpg',
* ]
*/
오픈 그래프와 비슷한 방식으로 트위터 카드 태그가 발견되지 않으면 배열이 비어 있습니다.
Content
Scraping Headings
제목은 웹 사이트의 콘텐츠에 대한 아이디어를 얻는 데 유용 할 수 있습니다. 다음 예는 스크레이핑 방법을 보여줍니다.
- 단일 제목
- 특정 수준의 모든 제목 (예 : <h3>)
- 페이지의 모든 제목
Scrape Single Heading
단일 제목을 스크래핑 하는 것은 쉽고 다음 예제에 따라 수행됩니다.
$web = new \spekulatius\phpscraper();
/**
* Navigate to the test page. It contains:
*
* <title>We are testing here!</title>
*/
$web->go('https://test-pages.phpscraper.de/content/online.html');
// Print the H1 heading
echo $web->h1[0]; // "We are testing here!"
웹 사이트 제목과 제목 1 (<h1>)은 다를 수 있습니다. 올바른 것을 검색했는지 확인하십시오.
Headings by Level
특정 수준의 모든 표제를 검색하려는 경우가 있을 수 있습니다. 아래 예는 이를 수행하는 방법을 보여줍니다.
$web = new \spekulatius\phpscraper();
/**
* Navigate to the test page. It contains:
*
* <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/online.html');
/**
* Get the h3 headings:
*
* [
* 'Example 1',
* 'Example 2',
* 'Example 3'
* ]
*/
$secondaryHeadings = $web->h3;
제목이 없으면 배열이 비어 있습니다.
All Headings on a Page
페이지의 모든 제목에 액세스하려면 1부터 6까지의 다른 수준에 액세스하여 액세스 할 수 있습니다. 또는 한 번에 모두 액세스 할 수 있습니다.
$web = new \spekulatius\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/online.html');
$headings = $web->headings;
/**
* $headings contains now:
*
* [
* [
* 'We are testing here!'
* ],
* [
* 'Examples'
* ],
* [
* 'Example 1',
* 'Example 2',
* 'Example 3',
* ],
* [],
* [],
* []
* ]
*/
보시다시피 여기에는 표제가 있는 구조에 대한 정보가 포함되어 있지 않습니다. 순전히 어떤 표제가 존재하는지 아는 것입니다. 개요가 있으면 관련 방법을 사용해야 합니다.
Scraping Text
PHP Scraper를 사용하면 대부분 단락인 내용을 스크랩 할 수 있습니다. 웹 사이트의 단락 (<p>)에 액세스하는 전용 방법이 있습니다. 다음 예는 웹 사이트의 콘텐츠 / 텍스트에 액세스하는 방법을 보여줍니다.
Getting all Paragraphs
다음 예제는 웹 사이트의 모든 단락 (<p>-태그) 목록을 반환합니다.
$web = new \spekulatius\phpscraper();
// Navigate to the test page. It contains 6 lorem ipsum paragraphs
$web->go('https://test-pages.phpscraper.de/content/paragraphs.html');
// check the number of paragraphs.
echo "This page contains " . count($web->paragraphs) . " paragraphs.\n\n";
// Loop through the paragraphs
foreach ($web->paragraphs as $paragraph) {
echo " - " . $paragraph . "\n";
}
/**
* Will print out:
*
* This page contains 6 paragraphs.
*
* - Maecenas eget ex sit amet urna porta fermentum at ut dui. Praesent lectus arcu, hendrerit sed mi vel, commodo lacinia velit. Nullam ac velit quis ante tristique scelerisque quis non metus. Pellentesque non aliquam elit, in tincidunt purus. Vestibulum fringilla cursus risus, eget ornare dolor feugiat vitae. Sed non porta lorem, eget ornare diam. Sed quam est, eleifend porttitor imperdiet sit amet, ultricies vel ipsum. Pellentesque mauris mauris, fermentum pretium ex quis, viverra mattis est. Donec laoreet sem nec arcu rhoncus lobortis. Duis id orci vel enim interdum aliquam. Integer eu ex ligula. Ut mattis nisi non malesuada ornare. In elit ligula, ultricies a aliquet eget, dictum sit amet neque. Quisque nulla sem, aliquam id molestie iaculis, consequat at augue. Nullam sollicitudin finibus eros in venenatis. Donec semper sagittis ipsum, et rhoncus magna ultricies eu.
* - Quisque sed dolor ut nunc accumsan lacinia. Suspendisse vel eros faucibus massa feugiat tristique. Nullam vitae scelerisque felis, malesuada hendrerit felis. Quisque eleifend mi lorem, vitae elementum dolor bibendum et. Etiam et faucibus augue. Pellentesque viverra sagittis consequat. Nulla a mollis ex. Sed vel nisl mauris. Nulla consequat dui sed pulvinar interdum. Integer vehicula molestie quam non fringilla. Duis auctor sem ut purus fringilla, in lacinia dui finibus. Nulla rhoncus semper velit, eget semper tellus suscipit eget. Vestibulum massa tellus, tristique sit amet dolor et, ullamcorper porta turpis. Vivamus eget magna lacinia, pretium sem sed, gravida libero.
* - Ut at nunc laoreet, vestibulum mauris in, volutpat magna. Aliquam sodales orci finibus porta convallis. Vestibulum sollicitudin felis a sem consequat luctus. Sed laoreet porta quam, non pharetra massa mattis semper. Phasellus aliquet tortor ut felis scelerisque, non dapibus justo tincidunt. Donec eu pulvinar nisi, sit amet elementum massa. Nulla in odio est. In neque ligula, tristique rhoncus orci eu, egestas ullamcorper est. Integer rhoncus vel quam vel placerat. In nec metus pellentesque elit accumsan molestie eu posuere odio. Sed at eros nec turpis vestibulum eleifend vel in erat. Etiam vel metus faucibus, tempus enim nec, elementum arcu. Ut nec blandit risus. Nam sapien nunc, tristique sit amet facilisis non, maximus a nulla. Pellentesque vel posuere libero.
* - Morbi volutpat purus odio, vitae scelerisque diam consectetur sed. Cras turpis leo, hendrerit in tempus et, convallis in nibh. Mauris molestie facilisis odio, ac egestas erat ultrices pellentesque. Donec interdum leo quis ipsum sagittis venenatis. Etiam scelerisque mi at metus ullamcorper, vitae tristique est tincidunt. Vestibulum ut congue urna, eu sagittis quam. Phasellus eget arcu sapien. In hac habitasse platea dictumst. Morbi ultrices, felis in faucibus ornare, libero augue scelerisque urna, et feugiat nisl est ut velit. Phasellus felis quam, egestas a faucibus nec, dictum eget enim. In tempor a lacus id facilisis.
* - Donec bibendum finibus neque quis viverra. Ut ut nulla venenatis, accumsan purus nec, ullamcorper nisi. Nulla bibendum dui sit amet velit venenatis, eget viverra nibh accumsan. Fusce pharetra, sem eu mattis varius, massa leo eleifend lectus, quis tempor elit ipsum sit amet lorem. Fusce viverra dictum tortor non sodales. Phasellus at lectus quis arcu finibus imperdiet sed eleifend nulla. Donec blandit egestas nibh ac euismod. Curabitur ac pretium eros.
* - Duis pharetra magna at dolor scelerisque, nec luctus ex pretium. Suspendisse a ante lectus. Donec vehicula condimentum turpis, in hendrerit dui suscipit non. Nullam a ultricies felis. Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Praesent aliquet varius mauris nec pretium. Vivamus convallis tincidunt nisi, eget scelerisque dolor facilisis vitae. Pellentesque purus neque, sollicitudin sit amet mauris id, posuere posuere mi. Etiam vitae urna vitae turpis volutpat consectetur. Quisque ultrices, ex dapibus hendrerit convallis, diam massa suscipit diam, vulputate pharetra mi orci at massa. Aliquam vel urna tempor, congue justo id, pulvinar lorem. Nulla mattis vitae justo sed molestie. Nunc fermentum fringilla nibh, id fermentum nulla. Sed tincidunt ipsum id est efficitur, molestie aliquet lacus hendrerit. Fusce et nisl eros.
*/
첫 번째 단락 스크랩
사이트의 첫 번째 단락을 스크래핑 하는 것은 배열의 첫 번째 요소 (인덱스 0)에 액세스하여 수행 할 수 있습니다.
$web = new \spekulatius\phpscraper();
$web->go('https://test-pages.phpscraper.de/content/paragraphs.html');
/**
* Prints the first paragraph:
*
* Maecenas eget ex sit amet urna porta fermentum at ut dui. Praesent lectus arcu, hendrerit sed mi vel, commodo lacinia velit. Nullam ac velit quis ante tristique scelerisque quis non metus. Pellentesque non aliquam elit, in tincidunt purus. Vestibulum fringilla cursus risus, eget ornare dolor feugiat vitae. Sed non porta lorem, eget ornare diam. Sed quam est, eleifend porttitor imperdiet sit amet, ultricies vel ipsum. Pellentesque mauris mauris, fermentum pretium ex quis, viverra mattis est. Donec laoreet sem nec arcu rhoncus lobortis. Duis id orci vel enim interdum aliquam. Integer eu ex ligula. Ut mattis nisi non malesuada ornare. In elit ligula, ultricies a aliquet eget, dictum sit amet neque. Quisque nulla sem, aliquam id molestie iaculis, consequat at augue. Nullam sollicitudin finibus eros in venenatis. Donec semper sagittis ipsum, et rhoncus magna ultricies eu.
*/
echo $web->paragraphs[0];
빈 p- 태그는 반환 된 배열에 빈 문자열로 이어집니다. 이를 방지하려면 대신 $ web-> cleanParagraphs를 호출 할 수 있습니다. 빈 단락을 필터링하고 내용이 있는 단락 만 반환합니다. 내용이 있는 첫 번째 단락에 액세스하려면 $ web-> cleanParagraphs [0]을 사용하십시오.
Export Content
예를 들어 처리 할 표제에만 액세스하고 싶을 수 있지만 표제 수나 길이가 항상 충분하지는 않을 수 있습니다. 어떤 경우에는 콘텐츠의 실제 구조를 식별해야 할 수도 있습니다. 이러한 사용 사례의 경우 다음 방법 중 하나를 고려할 수 있습니다.
- outline은 앞서 언급 한 표제 방법과 유사하게 작동합니다. 또한 모든 제목을 반환하지만 원본 문서의 구조를 그대로 유지하고 출력과 함께 제목 수준 (예 : h1) 만 제공합니다.
- outlineWithParagraphs는 outline과 비슷하게 작동하지만 이 호출에는 단락도 포함된다는 차이점이 있습니다.
- cleanOutlineWithParagraphs는 outlineWithParagraphs와 유사하게 작동하며, 차이점은 빈 HTML 태그가 제거됩니다.
다음 예제는 기능을 더 잘 이해하는 데 도움이 됩니다. 사용 가능한 키워드 추출 전용 방법이 있습니다.
Export the Outline
내용의 개요를 통해 문서의 색인을 작성할 수 있습니다. 다음 예제는 요청 된 문서에서 표제의 마크 다운 버전을 빌드합니다.
$web = new \spekulatius\phpscraper();
/**
* Navigate to the test page. This page contains:
*
* <h1>We are testing here!</h1>
* [...]
*
* <h2>Examples</h2>
* [...]
*
* <h3>Example 1</h3>
* [...]
*
* <h3>Example 2</h3>
* [...]
*
* <h3>Example 3</h3>
* [...]
*/
$web->go('https://test-pages.phpscraper.de/content/outline.html');
$outline = $web->outline;
/**
* $outline now contains:
*
* [
* [
* "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"
* ]
* ]
*/
Export the Outline with Paragraphs
다음 메서드는 개요와 비슷한 방식으로 작동하지만 반환 된 배열의 일부로 모든 단락도 포함합니다.
$web = new \spekulatius\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');
$content = $web->outlineWithParagraphs;
/**
* $content now contains:
*
* [
* [
* "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" => ""
* ]
* ]
*/
Export the Cleaned up Outline with Paragraphs
다음 메서드는 outlineWithParagraphs와 유사한 방식으로 작동하지만 반환 된 배열의 일부로 빈 빈 제목이나 단락을 포함하지 않습니다.
$web = new \spekulatius\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');
$content = $web->cleanOutlineWithParagraphs;
/**
* $content now contains:
*
* [
* [
* "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."
* ]
* ]
*/
Extract Keywords
콘텐츠 스크래핑만으로도 충분하지만 때로는 이 콘텐츠에서 중요한 용어와 구문 (키워드)을 추출해야 합니다. PHPScraper를 사용하면 웹 사이트의 키워드를 직접 추출 할 수 있습니다. 이를 위해 다음을 사용합니다.
- 웹 사이트의 제목,
- 메타 태그,
- 모든 제목,
- 페이지의 단락,
- 링크 앵커 및 링크 제목뿐만 아니라
- 이미지의 제목 속성
이러한 키워드 구문이 추출되었다고 해서 페이지가 이러한 키워드에 대해 실제로 순위를 매기는 것은 아닙니다. 웹 페이지가 순위를 매기는 키워드에 대한 최종 결정은 검색 엔진에 있습니다.
다음 예제는 웹 페이지에서 추출 된 모든 키워드 목록을 반환합니다.
$web = new \spekulatius\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 number of keywords.
$keywords = $web->contentKeywords;
echo "This page contains at least " . count($keywords) . " keywords/phrases.\n\n";
// Loop through the keywords
foreach ($keywords as $keyword) {
echo " - " . $keyword . "\n";
}
/**
* Will print out:
*
* This page contains at least 40 keywords/phrases.
*
* [...]
* - graphic
* - improper latin
* - introduced
* - keyword extraction tests
* - letraset transfer sheets
* - lorem ipsum
* - lorem ipsum php rake library lorem ipsum
* - lorem ipsum text
* - make
* - malorum
* - microsoft word
* - mid-1980s
* - nonsensical
* - page
* - paragraphs
* - philosopher cicero
* - php rake library
* - popular word processors including pages
* - popularized
* - removed
* - roman statesman
* - source
* [...]
*/
이에 대한 기본 언어 (로케일)는 en_US입니다. 다른 언어는 매개 변수로 전달할 수 있습니다. 이것은 현재 일부 언어에서만 작동합니다. 자세한 내용은 이 목록 (새 창에서 열림)을 확인하십시오.
Scoring of Keywords
모든 키워드가 검색 엔진의 순위 알고리즘에서 동일한 가중치를 갖는 것은 아닙니다. 여러 요소와 SEO 신호가 혼합되어 검색 엔진이 단어에 할당하는 가중치를 결정합니다. 단어의 빈도, 텍스트의 길이, 동의어와 같은 변형은 가중치가 다를 수 있습니다.
PHPScraper 라이브러리를 사용하면 점수 형식으로 키워드 가중치를 표시 할 수 있습니다.
$web = new \spekulatius\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 number of keywords.
$keywords = $web->contentKeywordsWithScores;
echo "This page contains at least " . count($keywords) . " keywords/phrases.\n\n";
// Loop through the keywords
foreach ($keywords as $keyword => $score) {
echo sprintf(" - %s (%s)\n", $keyword, $score);
}
/**
* Will print out:
*
* This page contains at least 40 keywords/phrases.
*
* [...]
* - 1960s (1.0)
* - 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)
* [...]
*/
PHP 함수 similar_text (새 창 열기) 및 levenshtein (새 창 열기)은 유사 키워드 및 키워드의 오타 변형을 식별하고 병합하는 데 도움이 될 수 있습니다. 키워드 병합 (새 창에서 열림)은 유사한 키워드를 분류하는 데 도움이 되는 작성기 패키지입니다.
Scraping Images
웹 사이트에서 이미지를 스크랩 하는 것은 다른 예와 유사한 접근 방식을 따릅니다. 이미지는 태그 속성과 같은 세부 정보를 사용하거나 URL 목록으로 만 구문 분석 할 수 있습니다.
Scraping Image URLs
다음 예제는 이미지에 대한 웹 페이지를 구문 분석하고 절대 URL을 배열로 반환합니다.
$web = new \spekulatius\phpscraper();
/**
* Navigate to the test page. This page contains two images:
*
* <img src="https://test-pages.phpscraper.de/assets/cat.jpg" alt="absolute path">
* <img src="/assets/cat.jpg" alt="relative path">
*/
$web->go('https://test-pages.phpscraper.de/meta/lorem-ipsum.html');
// Check if any images have been found
$images = $web->images;
if (count($images) > 0) {
var_dump($images);
/**
* [
* 'https://test-pages.phpscraper.de/assets/cat.jpg',
* 'https://test-pages.phpscraper.de/assets/cat.jpg',
* ]
*
* Note:
* Double because it's twice the same image:
* Once with a relative path and once with an absolute path.
* The relative paths are resolved to absolute paths by default.
*/
}
이미지가 없으면 배열이 비어 있습니다.
디테일이 있는 이미지 스크랩
더 자세한 정보가 필요한 경우 다음 요청을 통해 이미지 태그의 속성에 액세스 할 수 있습니다.
$web = new \spekulatius\phpscraper();
$web->go('https://test-pages.phpscraper.de/meta/lorem-ipsum.html');
var_dump($web->imagesWithDetails);
/**
* [
* '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,
* ]
*/
대체 텍스트 (콘텐츠 키워드 포함)는 이미지 기반 검색을 위해 검색 엔진에서 사용됩니다. 항상 정의해야 합니다.
스크래핑 속성 : Alt, 너비 및 높이
alt, width 및 height 속성은 자세한 데이터 세트에 포함됩니다.
더 많은 데이터가 필요한 경우 라이브러리를 확장하거나 고려할 문제를 제출해야 합니다.
Scraping Links
링크 스크래핑은 이미지 스크래핑과 매우 유사합니다. 추가 정보 없이 URL 목록과 rel, target 및 기타 속성이 포함 된 세부 목록을 검색 할 수 있습니다.
Simple Link List
다음 예제는 링크에 대한 웹 페이지를 구문 분석하고 절대 URL 배열을 반환합니다.
$web = new \spekulatius\phpscraper();
/**
* Navigate to the test page. It contains 6 links to placekitten.com with different attributes:
*
* <h2>Different ways to wrap the attributes</h2>
* <p><a href="https://placekitten.com/408/287" target=_blank>external kitten</a></p>
* <p><a href="https://placekitten.com/444/333" target="_blank">external kitten</a></p>
* <p><a href="https://placekitten.com/444/321" target='_blank'>external kitten</a></p>
*
* <h2>Named frame/window/tab</h2>
* <p><a href="https://placekitten.com/408/287" target=kitten>external kitten</a></p>
* <p><a href="https://placekitten.com/444/333" target="kitten">external kitten</a></p>
* <p><a href="https://placekitten.com/444/321" target='kitten'>external kitten</a></p>
*/
$web->go('https://test-pages.phpscraper.de/links/target.html');
// Print the number of links.
echo "This page contains " . count($web->links) . " links.\n\n";
// Loop through the links
foreach ($web->links as $link) {
echo " - " . $link . "\n";
}
/**
* Combined this will print out:
*
* This page contains 6 links.
*
* - 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
*/
페이지에 링크가 포함되어서는 안되는 경우 빈 배열이 반환됩니다.
Links with Details
더 자세한 정보가 필요한 경우 이미지에서와 유사한 방식으로 액세스 할 수 있습니다. 다음은 페이지의 첫 번째 링크의 세부 데이터에 액세스하는 예입니다.
$web = new \spekulatius\phpscraper();
/**
* Navigate to the test page. This page contains a number of links with different rel attributes. To save space only the first one:
*
* <a href="https://placekitten.com/432/287" rel="nofollow">external kitten</a>
*/
$web->go('https://test-pages.phpscraper.de/links/rel.html');
// Get the first link on the page.
$firstLink = $web->linksWithDetails[0];
/**
* $firstLink contains now:
*
* [
* 'url' => 'https://placekitten.com/432/287',
* 'text' => 'external kitten',
* 'title' => null,
* 'target' => null,
* 'rel' => 'nofollow',
* 'isNofollow' => true,
* 'isUGC' => false,
* 'isNoopener' => false,
* 'isNoreferrer' => false,
* ]
*/
더 많은 데이터가 필요한 경우 라이브러리를 확장하거나 고려할 문제를 제출해야 합니다.
Internal Links and External Links
PHPScraper는 내부 또는 외부 링크 만 반환 할 수 있습니다. 내부 링크에는 동일한 루트 도메인과 하위 도메인의 링크가 모두 포함됩니다. 정확한 하위 도메인 내의 링크 만 가져와야 하는 경우 대신 subdomainLinks를 사용하십시오. 다음은 둘 다 보여줍니다.
$web = new \spekulatius\phpscraper();
// Navigate to the test page.
$web->go('https://test-pages.phpscraper.de/links/base-href.html');
// Get the list of internal links (in the example an image is linked)
var_dump($web->internalLinks);
/**
* [
* 'https://test-pages.phpscraper.de/assets/cat.jpg'
* ]
*/
// Get the list of external links
var_dump($web->externalLinks);
/**
* [
* 'https://placekitten.com/408/287'
* ]
*/
Sub-domain Links
정확한 하위 도메인의 링크 만 검색해야 하는 경우 subdomainLinks-method를 사용할 수 있습니다.
$web = new \spekulatius\phpscraper();
// Navigate to the test page.
$web->go('https://test-pages.phpscraper.de/links/sub-domain-links.html');
var_dump($web->subdomainLinks);
/**
* [
* 'https://test-pages.phpscraper.de/',
* ]
*/
www가 하위 도메인으로 간주되기 때문에 사이트에서 'www'가 있는 링크와 없는 링크를 혼합 할 때 문제가 발생할 수 있습니다.
Navigation
PHPScraper는 대부분 웹 사이트를 구문 분석하고 정보를 수집하기 위한 것이지만 웹 사이트를 탐색하는 데 사용할 수도 있습니다. 다음은 웹 사이트를 서핑 하는 방법의 예입니다.
Navigation using URLs
모든 URL로 이동할 수 있습니다. 이러한 URL은 일반적으로 구문 분석 된 링크에서 가져옵니다.
$web = new \spekulatius\phpscraper();
// We start on test page #1.
$web->go('https://test-pages.phpscraper.de/navigation/1.html');
// Print the title to see if we actually at the right page...
echo $web->h1[0]; // 'Page #1'
// We navigate to the test page #2 using the absolute URL.
$web->clickLink('https://test-pages.phpscraper.de/navigation/2.html');
// Print the title to see if we actually at the right page...
echo $web->h1[0]; // 'Page #2'
Navigation using Anchor Texts
웹 사이트에서 앵커 텍스트를 사용하여 링크를 클릭 할 수 있습니다.
$web = new \spekulatius\phpscraper();
// We start on test page #1.
$web->go('https://test-pages.phpscraper.de/navigation/1.html');
/**
* This page contains:
*
* <a href="2.html">2 relative</a>
*/
// Print the title to see if we actually at the right page...
echo $web->h1[0]; // 'Page #1'
// We navigate to the test page #2 using the text it has on the page.
$web->clickLink('2 relative');
// Print the title to see if we actually at the right page...
echo $web->h1[0]; // 'Page #2'
이 기본 기능을 통해 웹 사이트를 탐색 할 수 있습니다.
More Examples
추가 예제가 필요한 경우 테스트를 확인하십시오 (새 창에서 열림). 여기에는 웹 사이트에서 데이터를 스크랩 하는 방법에 대한 추가 예제가 포함되어 있습니다.
- 이전글백엔드 마법사가 되기 위해 이러한 9 가지 백엔드 프레임 워크 중 하나에 집중 20.11.20
- 다음글PHP COVID-19 Statistics Checker 20.11.09