Selenium WebDriver 在子元素中查找元素

我试图使用 Selenium (Version 2.28.0)在子元素中搜索一个元素,但是 Selenium des 似乎没有将搜索限制在子元素中。是我做错了,还是有办法使用 element.find 来搜索子元素?

例如,我用这段代码创建了一个简单的测试网页:

<!DOCTYPE html>
<html>
<body>
<div class=div title=div1>
<h1>My First Heading</h1>
<p class='test'>My first paragraph.</p>
</div>
<div class=div title=div2>
<h1>My Second Heading</h1>
<p class='test'>My second paragraph.</p>
</div>
<div class=div title=div3>
<h1>My Third Heading</h1>
<p class='test'>My third paragraph.</p>
</div>
</body>
</html>

我的 python (Version 2.6)代码如下:

from selenium import webdriver


driver = webdriver.Firefox()


# Open the test page with this instance of Firefox


# element2 gets the second division as a web element
element2 = driver.find_element_by_xpath("//div[@title='div2']")


# Search second division for a paragraph with a class of 'test' and print the content
print element2.find_element_by_xpath("//p[@class='test']").text
# expected output: "My second paragraph."
# actual output: "My first paragraph."

如果我逃跑:

print element2.get_attribute('innerHTML')

它从第二个除法返回 html,因此 selenium 没有将搜索限制在 element2。

我希望能够找到 element 2的一个子元素。这篇文章建议我的代码应该工作 Selenium WebDriver 访问子元素,但是他的问题是由超时问题引起的。

有人能告诉我这是怎么回事吗?

97988 次浏览

If you start an XPath expression with //, it begins searching from the root of document. To search relative to a particular element, you should prepend the expression with . instead:

element2 = driver.find_element_by_xpath("//div[@title='div2']")
element2.find_element_by_xpath(".//p[@class='test']").text

Use the following:

element2 = driver.find_element_by_cssselector("css=div[title='div2']")
element2.find_element_by_cssselector("p[@class='test']").text

Please let me know if you have any problems.

This is how you search for element or tag in CSS subclass and I believe that it works for multilevel situation as well:

Sample HTML:

<li class="meta-item">
<span class="label">Posted:</span>
<time class="value" datetime="2019-03-22T09:46:24+01:00" pubdate="pubdate">22.03.2019 u 09:46</time>
</li>

This is how you would get pubdate tag value for example.

published = driver.find_element_by_css_selector('li>time').get_attribute('datetime')

Chrome Webdriver :

element = driver.find_element_by_id("ParentElement")
localElement = element.find_element_by_id("ChildElement")
print(localElement.text)

I guess,we need use method "By" from webdriver.common.by when use "driver.find_element".

So...the code must be:

from selenium import webdriver


driver = webdriver.Firefox()
from selenium.webdriver.common.by import By


element2 = driver.find_element(By.XPATH, "//div[@title='div2']")
element2.find_element(By.XPATH, ".//p[@class='test']").text

Find The Child of any Elements

parent = browser.find_element(by=By.XPATH,value='value of XPATH of Parents')
child=parent.find_elements(by=By.TAG_NAME,value='value of child path')