【问题标题】:extract image url from html page with php使用php从html页面中提取图像url
【发布时间】:2013-06-30 23:21:14
【问题描述】:

如何使用 php 从此链接中提取帖子图片?

我读到我不能用正则表达式来做。

http://www.huffingtonpost.it/2013/07/03/stupri-piazza-tahrir-durante-proteste-anti-morsi_n_3538921.html?utm_hp_ref=italy

非常感谢。

【问题讨论】:

标签: php regex image url html-parsing


【解决方案1】:
$content=file_get_contents($url);
if (preg_match("/<img.*src=\"(.*)\".*class=\".*pinit\".*>/", $content, $matches)) 
{
echo "Match was found <br />";
echo $matches[0];
}

$matches[0] 将打印整个图像标签。 如果您只想提取 URL,那么您可以使用 $matches[1] 来获得相同的结果:)

【讨论】:

  • 我正在尝试为“techcrunch.com/2014/05/09/facebook-is-down-for-many”做同样的事情,但它没有返回任何东西。我知道 在这里:tctechcrunch2011.files.wordpress.com/2014/05/…" class="" /> 但即使经过一些更改,它也不会返回任何内容。任何帮助都会很好_/_
  • 该正则表达式对于该特定网页中的模式非常具体。尝试这个。 if (preg_match("/";回声 $matches[0];工作:正则表达式将在图像标签中搜索 src 属性,然后提取假定在双引号内的图像 URL。您可以根据需要进行修改。
【解决方案2】:

您可以/必须使用 DOM 解析您的 html,以下是您的案例示例:

$curlResource = curl_init('http://www.huffingtonpost.it/2013/07/03/stupri-piazza-tahrir-durante-proteste-anti-morsi_n_3538921.html?utm_hp_ref=italy');
curl_setopt($curlResource, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curlResource, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($curlResource, CURLOPT_AUTOREFERER, true);

$page = curl_exec($curlResource);
curl_close($curlResource);


$domDocument = new DOMDocument();
$domDocument->loadHTML($page);

$xpath = new DOMXPath($domDocument);

$urlXpath = $xpath->query("//img[@id='img_caption_3538921']/@src");

$url = $urlXpath->item(0)->nodeValue;

echo $url;

花点时间学习一点 DOM 和 XPATH,这是值得的。

【讨论】:

    【解决方案3】:

    试试这个...

    $content=file_get_contents($url);
    if (preg_match("/src=[\"\'][^\'\']+[\"\']/", $content, $matches)) 
    {
        echo "Match was found <br />";
        echo $matches[0];
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-04-01
      • 1970-01-01
      • 2014-12-19
      • 2014-02-08
      • 1970-01-01
      • 1970-01-01
      • 2017-08-17
      相关资源
      最近更新 更多