DomCrawler filterXpath 并不总是提供完整 URL

DomCrawler filterXpath not always giving full URL

对于我的项目,我使用 domcrawler 来解析页面和提取图像。

代码:

$goutteClient = new Client();
$guzzleClient = new GuzzleClient(array(
    'timeout' => 15,
));

$goutteClient->setClient($guzzleClient);

try {
    $crawler = $goutteClient->request('GET', $url);
    $crawlerError = false;
} catch (RequestException $e) {
    $crawlerError = true;
}

if ($crawlerError == false) {

    //find open graph image
    try {
        $file = $crawler->filterXPath("//meta[@property='og:image']")->attr('content');
    } catch (\InvalidArgumentException $e) {
        $file = null;
    }

    //if that fails, find the biggest image in the DOM      
    if (!$file) {
        $images = $crawler
        ->filterXpath('//img')
        ->extract(array('src'));    

        $files = [];
        foreach ($images as $image) {

            $attributes = getimagesize($image);
            //stopping here since this is where i'm getting my error

相关部分在底部。这有时会起作用。但是,偶尔我会出错。例如,如果 $urlhttps://www.google.com,它将吐出以下错误:

ErrorException (E_WARNING) getimagesize(/images/branding/googlelogo/1x/googlelogo_white_background_color_272x92dp.png): failed to open stream: No such file or directory

如果我dd($image);在这种情况下,$image等于"/images/branding/googlelogo/1x/googlelogo_white_background_color_272x92dp.png"

但是,如果我尝试使用不给我错误的网站,例如 https://www.harvard.edudd($image); returns "https://www.harvard.edu/sites/default/files/feature_item_media/Kremer900x600.jpg"

换句话说,我没有得到完整的 URL。我该如何纠正?

在相关链接前加上方案和主机。您可以在 $url 上使用 parse_url 来提取方案和主机,并且可以在 $image 上使用相同的功能来检测是否设置了 scheme/host。