使用Yahoo YQL查询HTML

10

在尝试使用Yahoo Query Language和YQL提供的xpath功能解析HTML时,我遇到了无法提取“text()”或属性值的问题。
例如:
永久链接

select * from html where url="http://stackoverflow.com" 
and xpath='//div/h3/a'

提供XML格式的锚点列表

<results>
    <a class="question-hyperlink" href="/questions/661184/filling-the-text-area-with-the-text-when-a-button-is-clicked" title="In ASP.net, I need the code to fill the text area (in the form) when a button is clicked. Can you help me through by showing a simple .aspx code containing the script tag? ">Filling the text area with the text when a button is clicked</a>...
</results> 

现在,当我尝试使用

提取节点值时
select * from html where url="http://stackoverflow.com" 
and xpath='//div/h3/a/text()'

我得到的结果是连接在一起而不是一个节点列表,例如

<results>Xcode: attaching to a remote process for debuggingWhy is b
…… </results>

我该如何将其分离为节点列表并选择属性值?

像这样的查询:

select * from html where url="http://stackoverflow.com"
and xpath='//div/h3/a[@href]'

查询 div/h3/a 时给了我相同的结果

1个回答

20

YQL要求xpath表达式评估为itemPath而不是节点文本。但是一旦您拥有itemPath,您就可以从树中投影各种值

换句话说,ItemPath应该指向结果HTML中的节点而不是文本内容/属性。在选择* from data时,YQL返回所有匹配的节点及其子节点。

示例:

select * from html where url="http://stackoverflow.com" and xpath='//div/h3/a'

这将返回与xpath匹配的所有a。现在,要投影文本内容,您可以使用该标签投影出来。

select content from html where url="http://stackoverflow.com" and xpath='//div/h3/a'

"content" 返回节点中包含的文本内容。

要投射出属性,您可以将其相对于xpath表达式进行指定。在这种情况下,由于需要相对于a标签获取href属性,因此可以指定它。

select href from html where url="http://stackoverflow.com" and xpath='//div/h3/a'

这将返回如下结果:

<results> <a href="/questions/663973/putting-a-background-pictures-with-leds">putting a background pictures with leds</a> <a href="/questions/663013/advantages-and-disadvantages-of-popular-high-level-languages">advantages and disadvantages of popular high level languages</a> .... </results>

如果您需要同时获取'href'属性和'textContent'文本内容,可以执行以下YQL查询:

select href, content from html where url="http://stackoverflow.com" and xpath='//div/h3/a'

返回:

<results> <a href="/questions/663950/double-pointer-const-issue-issue">double pointer const issue issue</a>... </results>

希望这能有所帮助。如果您对YQL还有更多的问题,请告诉我。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接