【发布时间】:2011-03-06 05:11:12
【问题描述】:
首先,这是来自my previous question 的衍生品。我再次发布此消息是因为the person whose answer I accepted in the original post 建议我这样做,因为他认为这个问题以前没有正确定义。尝试2:
我正在尝试从this webpage 获取信息。为清楚起见,以下是页面源代码块的选择:
<p class="titlestyle">ANT101H5 Introduction to Biological Anthropology and Archaeology
<span class='distribution'>(SCI)</span></p>
<span class='normaltext'>
Anthropology is the global and holistic study of human biology and behaviour, and includes four subfields: biological anthropology, archaeology, sociocultural anthropology and linguistics. The material covered is directed to answering the question: What makes us human? This course is a survey of biological anthropology and archaeology. [<span class='Helpcourse'
onMouseover="showtip(this,event,'24 Lectures')"
onMouseout="hidetip()">24L</span>, <span class='Helpcourse'
onMouseover="showtip(this,event,'12 Tutorials')"
onMouseout="hidetip()">12T</span>]<br>
<span class='title2'>Exclusion: </span><a href='javascript:OpenCourse("WEBCOURSENOTFOUND.html")'>ANT100Y5</a><br>
<span class='title2'>Prerequisite: </span><a href='javascript:OpenCourse("WEBCOURSEANT102H5.pl?fv=1")'>ANT102H5</a><br>
从上面的示例块中,我想提取以下信息:
ANT101H5 Introduction to Biological Anthropology and ArchaeologyExclusion: ANT100Y5Prerequisite: ANT102H5
我想从网页中获取所有此类信息(请记住,某些课程可能还额外列出了“共同要求”,或者可能根本没有列出任何先决条件/共同要求或排除项)。
我一直在尝试为此任务编写一个合适的 xpath 表达式,但我似乎无法做到恰到好处。
到目前为止,在Dimitre Novatchev 的帮助下,我已经能够使用以下表达式:
sites = hxs.select("(//p[@class='titlestyle'])[2]/text()[1] | (//span[@class='title2'])[2]/text() | \
(//span[@class='title2'])[2]/following-sibling::a[1]/text() | (//span[@class='title2'])[3]/text() | \
(//span[@class='title2'])[3]/following-sibling::a[1]/text()")
但是,它会产生以下输出,似乎只获取页面上第一个课程的信息:
[{"desc": "ANT101H5 Introduction to Biological Anthropology and Archaeology \n "},
{"desc": "Exclusion: "},
{"desc": "ANT100Y5"},
{"desc": "Prerequisite: "},
{"desc": "ANT102H5"}]
绝对清楚,这个输出只有在它获得关于第一门课程的正确信息时才是正确的。我需要该网页上列出的所有课程的正确信息。
我已经很接近了,但我似乎无法弄清楚最后一步。
我会很感激任何帮助...在此先感谢
【问题讨论】:
-
抱歉,提供的文本不是格式良好的 XML。请改正。我可以尝试自己纠正这个问题,但我怎么能确定我“以正确的方式”纠正了它?
-
@inspectorG4dget:我发布了一个完整而简单的 XSLT 解决方案的答案。如果您仍然需要它,您可以从此 XSLT 代码生成您的单个 XPath 表达式。 :)
-
@inspectorG4dget:看起来你正在分组。这在 XPath 1.0 中是不可能的,因为节点集是一组唯一的无序节点。您必须选择组中的第一个(在本例中为
p元素),然后选择具有此节点作为上下文的组的其余部分。 -
@Dimitre:发布的 XML 是目标网页的直接摘录 - 我不知道您所说的“更正它”是什么意思。如果你能更具体一点,那么我可以尝试更有用
-
@Alejandro:这就是我想做的,因为我知道
p存在。我不知道其余的都这样。如果这不是我的代码所做的,请告知如何更改它