【问题标题】:How to Select Div within a Div with index in Xpath Syntax?如何在 Xpath 语法中使用索引的 Div 中选择 Div?
【发布时间】:2014-11-12 11:24:24
【问题描述】:
<div class="j-C j-C-yj" style="max-height: none; -moz-user-select: none; visibility: visible; left: 218px; top: 105px; display: none;" role="menu" aria-haspopup="true">
    <div id=":1r" class="j-qn" style="-moz-user-select: none;" role="separator"></div>
    <div id=":1u" class="j-qn" style="-moz-user-select: none;" role="separator"></div>
</div>

到目前为止,我正在创建 xpath 来选择 id=":1r" 为的元素

"(//div[包含(@class,'j-C') 和包含(@class,'j-C-yj')]/div)[1])"

我也试过

"(//div[包含(@class,'j-C') 和包含(@class,'j-C-yj')]/div)[1])"

但没有一个工作,请帮助!

P.S : 我找不到带有 id 的元素,因为页面的 id 是动态创建的

【问题讨论】:

    标签: python firefox selenium xpath


    【解决方案1】:

    只需使用xpath('.//div[contains(@class, "j-C") and contains(@class, "j-C-yj")]') 作为已经向您展示的另一个答案。

    其他更新:

    随着 OP 不断改变问题的约束,这里是完整的解决方案,完全符合 OP 的要求。

    示例:我正在使用 lxml 来解析您的字符串并执行 xpath

    from lxml import etree
    
    s = '''<div class="j-C j-C-yj" style="max-height: none; -moz-user-select: none; visibility: visible; left: 218px; top: 105px; display: none;" role="menu" aria-haspopup="true">
        ...:     <div id=":1r" class="j-qn" style="-moz-user-select: none;" role="separator"></div>
        ...:     <div id=":1u" class="j-qn" style="-moz-user-select: none;" role="separator"></div>
        ...: </div>'''
    
    # I need to wrap your string with <root> element otherwise first div will become the root
    tree = etree.fromstring('<root>'+s+'</root>')
    
    # xpath always returns a list, so just loop through the list and the first element is what you want
    for node in tree.xpath('.//div[contains(@class, "j-C") and contains(@class, "j-C-yj")]'):
        print etree.tostring(node[0])
    <div id=":1r" class="j-qn" style="-moz-user-select: none;" role="separator"/>
    

    【讨论】:

    • id 每次都会改变,所以我不能使用 id 来定位元素
    • @SalmanHasni,我已经更新了按class检索节点的答案。
    • 是的,课程保持不变
    • @SalmanHasni,所以基本上你不需要检查父 div,只需使用 j-qn 迭代所有 div class 你会得到你想要的然后检查节点的id
    • @SalmanHasni,哈哈,好吧。你真的应该把所有这些限制都放在 OP 上,这样人们才能确切地知道为什么以及你的预期输出是什么,我稍后会更新我的答案。
    【解决方案2】:

    似乎您的 xpath 接近尾声有问题。试试这段代码:

    driver.find_element_by_xpath("//div[contains(@class,'j-C') and contains(@class ,'j-C-yj')]/div[1]")
    

    【讨论】:

    • 请提供更多的html代码sn-p。我怀疑有多个具有“j-C j-C-yj”类的 div 元素,因此它无法检测到相关元素
    • 我有另一个 class='j-C j-C-yj tk-C' 的 div 会影响输出吗?
    • 它肯定会,如果这是父 div 并且它有多个元素 class='j-C j-C-yj'。在这种情况下,您的代码将无法单击指定的元素。这就是为什么我要求提供更完整的 HTML 代码 sn-p。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-24
    • 1970-01-01
    • 2011-07-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多