【问题标题】:XPath of text from child element子元素中文本的 XPath
【发布时间】:2017-03-29 15:19:05
【问题描述】:

我正在尝试使用 XPath 从网页中选择文本。检查元素后,我看到this。我正在尝试获取Florida State University。当我右键单击复制 XPath 时,我得到了这个:

//*[@id="clue_J_3_2"]/em

但是,当我运行 python 代码时:

from lxml import html
import requests
game_url = 'http://www.j-archive.com/showgame.php?game_id=5566'
page = requests.get(game_url)
tree = html.fromstring(page.content) 
path = '//*[@id="clue_J_3_2"]/em'
print tree.xpath(path)

我得到的输出是[]。我尝试了很多变体,包括:

  • //*[@id="clue_J_3_2"]/em/text()

  • /*/[@id="clue_J_3_2"]/em

  • //*[@id="clue_J_3_2"]//em[@class="correct_response"]/text()

请告诉我如何修复我的 XPath 以获得我想要的文本!

【问题讨论】:

    标签: python xml xpath


    【解决方案1】:

    您的 xpath 是正确的,但是您需要单击该元素才能在 DOM 中访问您想要的 xpath。当我检查有问题的页面时,我得到了这个。

    <div onmouseover="toggle('clue_J_3_2', 'clue_J_3_2_stuck', '(Grant: What is Florida?)<br /><br /><em class=&quot;correct_response&quot;>Florida State University</em><br /><br /><table width=&quot;100%&quot;><tr><td class=&quot;wrong&quot;>Grant</td><td class=&quot;right&quot;>Holly</td></tr></table>')" onmouseout="toggle('clue_J_3_2', 'clue_J_3_2_stuck', 'In 1858 this university went co-ed when it took on the Tallahassee Female Academy')" onclick="togglestick('clue_J_3_2_stuck')">
    

    所以,看来您必须自己解析divonmouseover。或者也许使用硒,但我不会走那么远。

    toggle_js = tree.xpath('//div[@onclick="togglestick(\'clue_J_3_2_stuck\')"]/@onmouseover')[0]
    # 'toggle(\'clue_J_3_2\', \'clue_J_3_2_stuck\', \'(Grant: What is Florida?)<br /><br /><em class="correct_response">Florida State University</em><br /><br /><table width="100%"><tr><td class="wrong">Grant</td><td class="right">Holly</td></tr></table>\')'
    answer = re.findall(r'correct_response">(.*)</em>', str(toggle_js))
    answer[0].strip() if answer else None
    # 'Florida State University'
    

    【讨论】:

      【解决方案2】:

      我检查了这个页面的源代码,我发现一些元素是由javascript动态创建的,因为request只能获取HTML代码,所以这就是为什么你在使用tree.xpath(path)时得到一个空结果的原因。
      在我将路径更改为'//*[@id="clue_J_3_2"] 后,我收到了一些文本。
      请记住,如果你想使用 print ,你应该这样做:print tree.xpath(path)[0].text

      【讨论】:

        猜你喜欢
        • 2015-02-14
        • 1970-01-01
        • 2020-03-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多