4

目标:我想使用 cURL 在 iframe 中抓取单词“Paris”。

假设您有一个包含 iframe 的简单页面:

<html>
<head>
<title>Curl into this page</title>
</head>
<body>

<iframe src="france.html" title="test" name="test">

</body>
</html>

iframe 页面:

<html>
<head>
<title>France</title>
</head>
<body>

<p>The Capital of France is: Paris</p>

</body>
</html>

我的卷曲脚本:

<?php>

// 1. initialize

$ch = curl_init();

// 2. The URL containing the iframe

$url = "http://localhost/test/index.html";

// 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("'The Capital of France is:(.*?). </p>'si", $output, $match);
if($match) 

// 7. Display the scraped string 

echo "The Capital of France is: ".$match[1];

?>

结果=没有!

谁能帮我找出法国的首都?!;)

我需要以下示例:

  1. 解析/抓取 iframe url
  2. 卷曲网址(就像我对 index.html 页面所做的那样)
  3. 解析字符串“Paris”

谢谢!

4

3 回答 3

3

--Edit-- 您可以将页面内容加载到字符串中,将字符串解析为 iframe,然后将 iframe 源加载到另一个字符串中。

$wrapperPage = file_get_contents('http://localhost/test/index.html');

$pattern = '/\.*src=\".*\.html"\.*/';

$iframeSrc = preg_match($pattern, $wrapperPage, $matches);

if (!isset($matches[0])) {
    throw new Exception('No match found!');
}

$src = $matches[0];

$src = str_ireplace('"', '', $src);
$src = str_ireplace('src=', '', $src);
$src = trim($src);

$iframeContents = file_get_contents($src);

var_dump($iframeContents);

- 原来的 -

努力提高你的接受率(接受以前回答的问题的答案)。

您将 curl 处理程序设置为的 url 是包装 i-frame 的文件,尝试将其设置为 iframe 的 url:

$url = "http://localhost/test/france.html";
于 2011-12-07T00:02:41.937 回答
3

请注意,有时由于各种原因,无法在自己的服务器上下文之外读取 iframe curl,并且直接查看 curl 会引发某种类型的“无法直接或从外部读取”错误消息。

在这些情况下,您可以使用 curl_setopt($ch, CURLOPT_REFERER, $fullpageurl); (如果您在 php 中并使用 curl_exec 阅读文本)然后 curl_exec 认为 iframe 在原始页面中,您可以阅读源代码。

因此,如果由于某种原因无法在包含它作为 iframe 的较大页面的上下文之外读取 france.html,您仍然可以使用上述方法获取源代码,使用 CURLOPT_REFERER 并设置主页(test/index.html in原始问题)作为推荐人。

于 2013-06-26T18:09:24.103 回答
2

要回答您的问题,您的模式与输入文本不匹配:

          <p>The Capitol of France is: Paris</p>

您在结束段落标记之前有一个额外的空格,它永远不会匹配:

preg_match("'The Capitol of France is:(.*?). </p>'si"

您应该在捕获组之前有空间,然后删除多余的空间.

preg_match("'The Capitol of France is: (.*?)</p>'si"

要在两个位置中的任何一个处使用可选空间,请\s*改用:

preg_match("'The Capitol of France is:\s*(.*?)\s*</p>'si"

您还可以使捕获组只匹配(\w+)更具体的字母。

于 2011-12-07T00:07:11.090 回答