有没有办法让YQL返回HTML?

时间:2010-04-02 16:35:39

标签: html xpath yahoo-pipes yql

我正在尝试使用YQL从一系列网页中提取HTML的一部分。页面本身的结构略有不同(因此Yahoo Pipes“获取页面”及其“剪切内容”功能效果不佳)但我感兴趣的片段始终具有相同的class属性。

如果我有这样的HTML页面:

<html>
  <body>
    <div class="foo">
      <p>Wolf</p>
      <ul>
        <li>Dog</li>
        <li>Cat</li>
      </ul>
    </div>
  </body>
</html>

并使用如下的YQL表达式:

SELECT * FROM html 
WHERE url="http://example.com/containing-the-fragment-above" 
AND xpath="//div[@class='foo']"

我得到的是(显然是无序的?)DOM元素,我想要的是HTML内容本身。我也试过了SELECT content,但只选择了文字内容。我想要HTML。这可能吗?

3 个答案:

答案 0 :(得分:8)

你可以写一点Open Data Table来发送一个正常的YQL html表查询和 stringify 结果。如下所示:

<?xml version="1.0" encoding="UTF-8" ?>
<table xmlns="http://query.yahooapis.com/v1/schema/table.xsd">
  <meta>
    <sampleQuery>select * from {table} where url="http://finance.yahoo.com/q?s=yhoo" and xpath='//div[@id="yfi_headlines"]/div[2]/ul/li/a'</sampleQuery>
    <description>Retrieve HTML document fragments</description>
    <author>Peter Cowburn</author>
  </meta>
  <bindings>
    <select itemPath="result.html" produces="JSON">
      <inputs>
        <key id="url" type="xs:string" paramType="variable" required="true"/>
        <key id="xpath" type="xs:string" paramType="variable" required="true"/>
      </inputs>
      <execute><![CDATA[
var results = y.query("select * from html where url=@url and xpath=@xpath", {url:url, xpath:xpath}).results.*;
var html_strings = [];
for each (var item in results) html_strings.push(item.toXMLString());
response.object = {html: html_strings};
]]></execute>
    </select>
  </bindings>
</table>

然后,您可以使用YQL查询查询该自定义表,如:

use "http://url.to/your/datatable.xml" as html.tostring;
select * from html.tostring where 
  url="http://finance.yahoo.com/q?s=yhoo" 
  and xpath='//div[@id="yfi_headlines"]/div[2]/ul/li'

编辑:刚刚意识到这是一个非常古老的问题,而且已经被撞了;至少答案就在这里,对于任何在这个问题上磕磕绊绊的人来说。 :)

答案 1 :(得分:2)

我有同样的问题。我唯一能解决的问题是避免使用YQL,只使用正则表达式来匹配开始和结束标记:/。不是最好的解决方案,但如果html相对不变,并且模式只是说<div class='name'><div class='just_after&gt;`,那么你可以侥幸逃脱。然后你可以得到之间的HTML。

答案 2 :(得分:0)

YQL将页面转换为XML,然后对其执行XPath,然后获取DOMNodeList并将其序列化为输出的XML(如果需要,则转换为JSON)。您无法访问原始数据。

为什么不能处理XML而不是HTML?