【问题标题】:Xpath union multiple queriesXpath 联合多个查询
【发布时间】:2014-03-27 13:54:54
【问题描述】:

我正在从另一个网站取消工作。源网站有不同的情况,因为用户复制粘贴数据和结构更改。

案例一:

<h3>Job Description</h3>
<div style="text-align: justify; line-height: 115%"><b>
Receptionist is assigned for ANAFAE-ALC based in Mazar-e-Sharif. This position is supervised by and reports to ALC Educational Program Manager and following are the main duties but are not limited to that.</div>

案例 2:

<h3>Job Description</h3>
<p>
Receptionist is assigned for ANAFAE-ALC based in Mazar-e-Sharif. This position is supervised by and reports to ALC Educational Program Manager and following are the main duties but are not limited to that.</p>

在这种情况下,p 标签有时会替换其他 html 标签。

案例 3:

<h3>Job Description</h3>
Receptionist is assigned for ANAFAE-ALC based in Mazar-e-Sharif. This position is supervised by and reports to ALC Educational Program Manager and following are the main duties but are not limited to that.

我正在使用这个字符串来获取内容。这现在适用于案例 3,但不适用于其他两种情况。如何修复 t 以适用于所有三种情况。

//text()[preceding::h3[text()="Job Description"]

【问题讨论】:

    标签: php xpath web-scraping


    【解决方案1】:

    您的 XPath 表达式选择前面带有 &lt;h3&gt; 且文本节点等于“职位描述”的文本节点。这仅匹配第三种情况,因为前两种情况分别在&lt;h3&gt; 之后有一个&lt;div&gt; 和一个&lt;p&gt;

    你可以试试这样的:

    //node()[preceding-sibling::*[1][self::h3 = "Job Description"]]/string()
    

    一些细节:

    //node() 从初始上下文中选择所有元素或文本节点后代。

    preceding-sibling::*[1] 选择前一个元素。

    [self::h3 = "Job Description"] 检查元素是否为&lt;h3&gt;,并且其字符串值等于“职位描述”。

    /string() 返回上下文节点的字符串值。对于您的示例内容,可以使用/descendant-or-self::text()。如果它是一个文本节点,它通过选择上下文节点来工作,如果它是一个元素,它会选择所有后代文本节点。但是,如果将 &lt;div&gt;&lt;p&gt; 更改为具有混合内容(即,散布有文本节点的子元素),则该表达式将返回后代文本节点的序列,而 /string() 会将它们连接在一起。

    【讨论】:

    • 它不返回任何东西。这是我现在拥有的完整字符串。 //node()[preceding-sibling::*[1][self::h3 = "Job Description"]]/descendant-or-self::text() and following-sibling::h3[text()="Job Requirements"]]
    • XPath 表达式的执行环境是什么?你是怎么运行这个的?
    • 这工作://node()[preceding::h3[node()="Contact Information"]
    猜你喜欢
    • 2020-12-17
    • 2022-12-10
    • 1970-01-01
    • 1970-01-01
    • 2019-12-04
    • 1970-01-01
    • 1970-01-01
    • 2015-03-18
    • 2011-05-09
    相关资源
    最近更新 更多