【问题标题】:Scraping html with urls from website使用网站中的 url 抓取 html
【发布时间】:2015-05-16 08:34:45
【问题描述】:

我正在使用 php simple html dom 从网站上抓取一些 html,其中包括几张图片。
但是图片没有正确指向网站。例如,下面是其中一张图片的示例,您可以看到它没有指向该网站。
是否可以动态更改 URL 以指向该网站

http://www.url.com/bilder/flags_long/United States.gif

html 示例

<img src="/bilder/flags_long/United States.gif" align="absmiddle" title="United States" alt="United States" border="0">

示例代码:

include('simple_html_dom.php');
$sum_gosu = file_get_html("http://www.gosugamers.net/counterstrike/news/30995-starladder-is-back-with-the-thirteenth-edition-of-starseries");
$gosu_full = $sum_gosu->find("//div[@class='content light']/div[@class='text clearfix']/div", 0);

【问题讨论】:

  • 您可以将两个文本连接在一起。我的意思是网站 URL 和图像 URL。 $URL=$PageURL.$IMGsrc

标签: php html web-scraping simple-html-dom


【解决方案1】:

如何连接您从中获​​取文档的实际 URL 和相对图像路径。只是提供一个想法(这未经测试,您绝对应该检查图像 src 属性在某些情况下是相对的还是绝对的):

<?php
    $url = 'http://www.url.com/';
    $html = file_get_html($url);
    $images = array();

    foreach($html->find('img') as $img) {

        // Option 1: Fill your images array (in case you only need the images)
        $images[] = rtrim($url, '/') . '/' . ltrim($img->src, '/');

        // Option 2: Update $img->src inside your $html document
        $img->src = rtrim($url, '/') . '/' . ltrim($img->src, '/');

    }

?>

更新根据您的示例代码,我的示例可能如下所示:

<?php
    include('simple_html_dom.php');
    $sum_gosu_url = "http://www.gosugamers.net/counterstrike/news/30995-starladder-is-back-with-the-thirteenth-edition-of-starseries";
    $sum_gosu = file_get_html($sum_gosu_url);
    $gosu_full = $sum_gosu->find("//div[@class='content light']/div[@class='text clearfix']/div", 0);

    foreach($gosu_full->find('img') as $img) {
        $img->src = $sum_gosu_url . $img->src;
    }
?>

之后,您的 $gosu_full 文档中的 img src 属性应该是固定和可解析的(可由客户端下载)。希望这会有所帮助,并且我实际上正在理解您的问题:)

【讨论】:

  • 我的意思是我有一个很长的字符串,其中包含许多 html 标签,还有图像。如果这些图像不起作用,我想更改为正确的路径
  • 那么字符串实际上是从哪里来的呢?它是您的 Web 服务器上的文件还是您从远程 URL 获取的页面?因为您肯定需要知道必须使用哪个 URL 为图像的相对路径添加前缀,在第一种情况下是您自己的域,在第二种情况下是您从中获取 html 文档的域。对不起,当我弄错时,但这就是我所理解的:)
  • 如果我错了,请发布一些示例代码如何加载您的 html 字符串。
  • 我可以通过传递 $img = ""; 来删除图像吗?在循环内部?
  • 我认为您可以尝试使用 unset($img),我可以想象 simple-html-dom 库会适当地取消设置它,但我还没有仔细研究它们的实现
【解决方案2】:
$url="http://www.url.com";
$Chtml = file_get_html($url);
$imgurl=Chtml->find("img",0)->src;
echo $url.$imgurl;

【讨论】:

  • 不错!关于代码的一些基本解释以及它如何回答问题将非常有帮助。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-20
  • 1970-01-01
相关资源
最近更新 更多