<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 =&#34;的元素:1r&#34;是
&#34;(// div [contains(@class,&#39; j-C&#39;)并包含(@class,&#39; jC-yj&#39;)] / div)[ 1])&#34;
我也试过了
&#34;(// div [contains(@class,&#39; j-C&#39;)并包含(@class,&#39; jC-yj&#39;)] / div)[ 1])&#34;
但是没有工作请帮助!
P.S:我找不到带id的元素,因为页面的id是动态创建的
答案 0 :(得分:1)
好像你的xpath中有一个问题。试试这段代码:
driver.find_element_by_xpath("//div[contains(@class,'j-C') and contains(@class ,'j-C-yj')]/div[1]")
答案 1 :(得分: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"/>