【问题标题】:Pulling from another website从另一个网站拉取
【发布时间】:2014-07-24 06:14:22
【问题描述】:

我试图将跨度类从一个网站拉到另一个网站,但似乎无法使其工作。是否可以使用 curl 从不同的网站获取单个单词?

span 类的正确语法是什么?使用我的代码,我收到警告:

Notice: Trying to get property of non-object in /Applications/XAMPP/xamppfiles/htdocs/uptickgather.php on line 25

我的代码:

<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://quotes.wsj.com/UEPS');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
libxml_use_internal_errors(true);
$html = curl_exec($ch); // the whole document (in string) goes in here
$dom = new DOMDocument();
$dom->loadHTML($html); // load it
libxml_clear_errors();
$xpath = new DOMXpath($dom); 

$class = $xpath->query('//[@class="cr_info info_price price_l"]//');
echo $class->nodeValue . ' ';
?>

第 25 行是:

echo $class->nodeValue . ' ';

到目前为止,我已尝试更改查询格式以使用 @ 语法。因此我尝试使用单斜杠,尽管据我了解,双斜杠会显示名称为

的所有属性
"cr_info info_price price_l"

我还尝试使用以下内容:

$class = $xpath->query('//[@class="cr_info info_price price_l"]//');

但是,我似乎无法让它工作。有没有在 xpath/curl 方面有更多经验的人对如何解决这个问题有任何建议?

编辑:当我使用 var dump 时,它看起来像:

object(DOMNodeList)#3 (1) { ["length"]=> int(0) }

但我正试图重新开始编码,但我完全迷失了方向。有人可以帮忙吗?

【问题讨论】:

  • 那么第 25 行在哪里?是 DOMDocument 对象还是 CURL 对象导致了错误?到目前为止,您尝试过哪些调试策略?
  • 它应该回显什么?让我知道我会帮你废弃这个 html
  • 它应该与股票价格相呼应。
  • 你检查过$class吗? xquery 函数将在失败时返回 false(因此 $class 将是布尔值,而不是对象)。成功时,它返回一个 DOMNodeList,而不是一个简单的对象。您需要使用正确的 getattribute 方法。
  • Kainaw,你把我弄丢了,对不起,我是新手。你能再解释一下吗?

标签: php html dom curl xpath


【解决方案1】:

我建议结合以下 2 个类从另一个网站提取信息:

从任何 HTML 标签、内容或标签属性中提取信息:http://simplehtmldom.sourceforge.net/

易于处理 curl,支持 POST 请求:https://github.com/php-curl-class/php-curl-class

所以,在你的例子中:

//download and include the 2 classes:
include('path/to/curl.php');
include('path/to/simple_html_dom.php');
$url = 'http://quotes.wsj.com/UEPS';

$curl = new Curl;
$html = str_get_html($curl->get($url)); //pull all html of a website
$span = $html->find('span[class="cr_info info_price price_l"]',0)->plaintext; //find span tag that contains the following class, 0 means that it is first element that matches tag span and that class, plaintext means it will remove tags leaving only text within tag    
echo $span; //contents of span, e.g. $ 10.811 USD

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-01-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-15
    • 1970-01-01
    相关资源
    最近更新 更多