我正在使用"@nesk/puphpeteer": "^2.0.0" Link to Github-Repo,希望从链接中获取文本和href-attribute。
我尝试了以下几种方法:
<?php
require_once '../vendor/autoload.php';
use Nesk\Puphpeteer\Puppeteer;
use Nesk\Rialto\Data\JsFunction;
$debug = true;
$puppeteer = new Puppeteer([
'read_timeout' => 100,
'debug' => $debug,
]);
$browser = $puppeteer->launch([
'headless' => !$debug,
'ignoreHTTPSErrors' => true,
]);
$page = $browser->newPage();
$page->goto('http://example.python-scraping.com/');
//get text and link
$links = $page->querySelectorXPath('//*[@id="results"]/table/tbody/tr/td/div/a', JsFunction::createWithParameters(['node'])
->body('return node.textContent;'));
// iterate over links and print each link and its text
// get single text
$singleText = $page->querySelectorXPath('//*[@id="pagination"]/a', JsFunction::createWithParameters(['node'])
->body('return node.textContent;'));
$browser->close();当我运行上面的脚本时,我从页面获得了节点,但是我不能访问属性或文本?
有什么建议要怎么做吗?
感谢您的回复!
发布于 2021-09-17 22:40:49
querySelectorXPath返回ElementHandle的数组。还有一件事querySelectorXPath不支持回调函数。
首先获取所有节点ElementHandle
$links = $page->querySelectorXPath('//*[@id="results"]/table/tbody/tr/td/div/a');然后遍历链接以访问节点的属性或文本
foreach($links as $link){
// for text
$text = $link->evaluate(JsFunction::createWithParameters(['node'])
->body('return node.innerText;'));
// for link
$link = $link->evaluate(JsFunction::createWithParameters(['node'])
->body('return node.href;'));
}发布于 2021-09-14 19:05:28
免责声明:这只是一个中间答案-一旦我对HTML属性或其他需要检索的期望有更多的具体要求,我会立即更新。
tl;dr:提到的composer package nesk/puphpeteer实际上只是一个基于底层NodeJS的puppeteer实现的包装器。因此,访问数据和结构必须与其JavaScript对应物“相似”……
也许Codeception (无头)或symfony/dom-crawler (原始标记)可能是更好、更成熟的替代方案。
不管怎样,让我们从上面的例子中一步一步地来看一遍:
$links = $page->querySelectorXPath(
'//*[@id="results"]/table/tbody/tr/td/div/a',
JsFunction::createWithParameters(['node'])->body('return node.textContent;')
);access to> $x() would result in an array of ElementHandle items
ElementHandle.getProperty(prop)
node.textContent (从JsFunction导出),相应的数据获取一个标量值(to PHP)然后就完成了via ElementHandle.jsonValue()因此,在那之后,我们会得到类似这样的东西:
$links = $page->querySelectorXPath(
'//*[@id="results"]/table/tbody/tr/td/div/a',
JsFunction::createWithParameters(['node'])->body('return node.textContent;')
);
/** @var \Nesk\Puphpeteer\Resources\ElementHandle $link */
foreach ($links as $link) {
var_dump($link->getProperty('textContent')->jsonValue());
}它输出以下原始数据(从http://example.python-scraping.com/检索):
string(12) " Afghanistan"
string(14) " Aland Islands"
string(8) " Albania"
string(8) " Algeria"
string(15) " American Samoa"
string(8) " Andorra"
string(7) " Angola"
string(9) " Anguilla"
string(11) " Antarctica"
string(20) " Antigua and Barbuda"https://stackoverflow.com/questions/68717664
复制相似问题