在尝试使用YQL提供的Yahoo Query Language和xpath功能解析html时,我遇到了无法提取“text()”或属性值的问题。
例如
perma link
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
答案 0 :(得分:20)
YQL要求xpath表达式计算为itemPath而不是节点文本。但是一旦你有了一个itemPath,你可以从树中投射各种值
换句话说,ItemPath应该指向结果HTML中的节点而不是文本内容/属性。当您从数据中选择*时,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表达式指定它。在这种情况下,因为您需要相对于。
的hrefselect href from html where url="http://stackoverflow.com" and xpath='//div/h3/a'
这会返回
<results>
<a href="/questions/663973/putting-a-background-pictures-with-leds"/>
<a href="/questions/663013/advantages-and-disadvantages-of-popular-high-level-languages"/>
....
</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有更多疑问,请与我们联系。