【问题标题】:Scraping iframe content using Curl php使用 Curl php 抓取 iframe 内容
【发布时间】:2015-10-11 06:40:32
【问题描述】:

我正在尝试从另一个域中抓取通过 iframe 生成的 cmets。 当我尝试这样做时,我要么收到一条空消息,说明此应用程序未注册。我知道这是由于跨域问题造成的。我使用 Curl 在 php 中编写了以下代码。当我传递父级时url 它加载页面,但 iframe 下的内容丢失,当我传递子 url 时,它返回一条消息说应用程序未注册。

代码:

<?php

// 1. initialize

$ch = curl_init();

// 2. The URL containing the iframe

$url = "http://www.ndtv.com/india-news/1993-mumbai-blasts-convict-yakub-    memons-final-mercy-plea-rejected-783656?pfrom=home-lateststories";

// 3. set the options, including the url

curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 2);
curl_setopt($ch, CURLOPT_MAXREDIRS, 10);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);

// 4. execute and fetch the resulting HTML output by putting into $output
$output = curl_exec($ch);

// 5. free up the curl handle  
curl_close($ch);

// 6. Scrape for a single string/word ("Paris")  
preg_match("~</?p[^>]*>~", $output, $match);
   if($match)

// 7. Display the scraped string  
echo $output;
?>

iframe 的子 url 是

http://social.ndtv.com/static/Comment/Widget/?&key=68a2a311a51a713dad2e777d65ec4db4&link=http%3A%2F%2Fwww.ndtv.com%2Findia-news%2F1993-mumbai-blasts-convict-yakub-memons-final-mercy-plea-rejected-783656&title=Yakub+Memon+to+Hang+On+July+30+for+India%27s+Deadliest+Terror+Attack&ctype=story-news&identifier=story-news-783656&enableCommentsSubscription=1&ver=1&reply=1&sorted_by=likes

我有什么方法可以访问 iframe 内容。我想要这种数据形式分析,而不是用于任何非法用途。

提前感谢您的帮助。

【问题讨论】:

  • 如果 cmets 是使用 JavaScript 动态加载的,那么 cURL 或 PHP 将无法神奇地加载它们。您需要使用 PhantomJS 之类的东西来模拟加载页面的浏览器,然后从中提取结果。
  • 这里并非完全如此。您可以获得前 20 个 cmets,之后您就不能只使用 Curl
  • @PHPhil 感谢您的回复,但您能否通过修改我的代码来帮助我获得前 20 个 cmets,这将是一个很好的临时解决方案。
  • @Mr.Llama 如果我按照建议使用 PhantomJS,我是否能够浏览子 iframe,否则我可能会因跨域问题而被拒绝

标签: javascript php html curl iframe


【解决方案1】:

您需要实际解析 HTML...正则表达式不适用于 html。

见:RegEx match open tags except XHTML self-contained tags

【讨论】:

  • 这不是问题,由于交叉浏览问题,我无法浏览我的 iframe 任何建议???
  • 啊。误解了。如果你 curl iframe url 怎么办?
  • 对不起...当我卷曲 iframe 网址时,它说应用程序未注册,因为 iframe 位于另一个域中
  • 我可以访问 url.. 我不明白为什么 curl 请求不能。
  • 嗨@Half Crazed 感谢您尝试这就是我的意思,由于子域的安全问题,您无法访问它,即 iframe url 域与父 url 的域不同(主页)..是否有任何黑客可以绕过此安全身份验证。
【解决方案2】:

如果您想要讨论 cmets,则需要获取评论部分的 iframe URL,而不是包含 iframe 的页面。 cURL 只是返回 URL 的源代码,它不会递归地跟随 iframe 链接并嵌入它们。

【讨论】:

  • Llama 我确实尝试传递 iframe url,但它返回一条消息说应用程序未注册。请帮助
猜你喜欢
  • 2012-01-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-01-04
  • 2010-10-29
  • 1970-01-01
相关资源
最近更新 更多