【问题标题】:PHP DOMXpath not scraping URLPHP DOMXpath 不抓取 URL
【发布时间】:2012-10-19 00:04:14
【问题描述】:

我正在尝试获取这些标签之间的数据:

<item><title>White Paper and Sales copy writer by stelladonsai</title>
<link>http://www.freelancer.com/projects/Technical-Writing-Academic-Writing/White-Paper-Sales-copy-writer.html</link>
<description>I need native English speaker to write a piece of white paper and a Sales copy.    *you must have experience.   *you must be native English speaker  *you must have sample to be attached with your cover... (Budget: &#36;30-&#36;250 USD, Jobs: Academic Writing, Technical Writing)</description>
<pubDate>Thu, 18 Oct 2012 17:23:10 -0400</pubDate>
<guid isPermaLink="false">Freelancer.com_project_2578329</guid>
</item>

我使用的 PHP 代码是:

$html = new DOMDocument();
@$html->loadHTML($txt);
$xpath = new DOMXPath( $html );

/*Begin Get Titles*/
$bquery = $xpath->query( "//item/title" );
$i=0;
foreach ($bquery as $b){
    $i=$i+1;
    $title[$i] = $b->nodeValue; 
}
/*End Get Titles*/

/*Begin Get Links*/
$bquery = $xpath->query( "//item/link" );
$i=0;
foreach ($bquery as $b){
    $i=$i+1;
    $link[$i] = $b->nodeValue;  
}
/*End Get Links*/

$txt 来自我用 CURL 抓取的 RSS 提要。上面的代码可以很好地获得标题,以及我想要的任何其他字段。但是当我尝试抓取并回显链接字段时,我什么也得不到。 (我尝试用其他字段替换 //item/link 并且它们都有效)。

不知道我在这里做错了什么,非常感谢所有帮助。

【问题讨论】:

    标签: php xpath web-scraping domxpath


    【解决方案1】:

    使用 loadXML 而不是 loadHTML,因为您加载的是 XML 而不是 html。

    http://codepad.org/0FYXiwMy

    【讨论】:

    • 当我使用该代码时,我收到此错误:警告:DOMDocument::loadXML() [domdocument.loadxml]:需要开始标签,在实体中找不到'stackoverflow.com/questions/6736925/… 我正在用 CURL 收集的提要在这里:freelancer.com/rss/job_Academic-Writing.xml
    • 对不起,我早点进入。也很抱歉评论格式错误。仍然习惯于stackoverflow。谢谢你帮助我!
    • @user1757890 您发布的 xml 不是提要返回的内容?
    • 这是提要返回的内容。每个工作的数据都在“项目”标签之间,我刚刚发布了 1 个项目标签并删除了类别和合作:关键字标签,因为我试图保持我的帖子简短,我现在只是想抓住链接。我认为其余的没有任何影响。我已经尝试并成功地呼应了 guid、pubDate、描述和标题。链接是唯一不显示的东西。
    • 我刚刚意识到它可能无法正常工作,因为 html 中的链接标签没有打开和关闭它之间的数据。例如: 现在想办法解决这个问题..
    猜你喜欢
    • 1970-01-01
    • 2014-10-31
    • 2012-05-10
    • 2013-04-09
    • 2013-02-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多