python + selenium是否有任何方法可以找到父元素,兄弟元素或子元素,就像
driver.find_element_parent?
或
driver.find_element_next?
或
driver.find_element_previous
?
例如:
<tr>
<td>
<select>
<option value=0, selected='selected'> </option>
<option value=1, > </option>
<option value=2,> </option>
</select>
</td>
<td> 'abcd'
<input name='A'> </input>
<td>
<tr>
我已经尝试如下,但失败了:
input_el=driver.find_element_by_name('A')
td_p_input=find_element_by_xpath('ancestor::input')
如何获取输入元素的父元素,然后最后选择选项?
您可以使用 ..
xpath 找到父元素:
input_el = driver.find_element_by_name('A')
td_p_input = input_el.find_element_by_xpath('..')
为获得选定的选项创建一个单独的 xpath 怎么样,如下所示:
selected_option = driver.find_element_by_xpath('//option[@selected="selected"]')
从您的示例中,我认为您只希望表行中的选定选项当且仅当该行还具有名称为“A”的输入元素时,无论该元素在 html-tree 中的哪个位置位于该行下方 -元素。
您可以通过 xpath 祖先轴来实现这一点。
为了更好的可读性,我将逐步展示如何执行此操作(但实际上您可以将所有内容放在一个 xpath 表达式中):
# first find your "A" named element
namedInput = driver.find_element_by_name("A");
# from there find all ancestors (parents, grandparents,...) that are a table row 'tr'
rowElement = namedInput.find_element_by_xpath(".//ancestor::tr");
# from there find the first "selected" tagged option
selectedOption = rowElement.find_element_by_xpath(".//option[@selected='selected']");
导航到同一层次结构下的元素的一种可能方法是在 xpath 中使用 /../
,如下所示:
current_element = driver.find_element_by_xpath('//android.view.ViewGroup/android.widget.RelativeLayout/android.widget.TextView[@text="Current element text"]/../android.widget.TextView[@text="Next element text"]')
在这里它将:
首先导航到 android.widget.TextView[@text = "Current element text"] 然后它会回到父元素,即 android.widget.RelativeLayout 并选择下一个 android.widget.TextView[@text="Next element text" ] 在同一层次结构下。
driver.find_element_by_xpath("//div[contains(text(),'floor price')]/../div").text
不定期副业成功案例分享
../
语法不起作用,./..
和./../..
按预期工作。不要添加尾部斜杠。