Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/selenium/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jsf-2/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 使用XPath和Selenium将任意文档元素作为根_Python_Selenium_Selenium Webdriver_Dom_Xpath - Fatal编程技术网

Python 使用XPath和Selenium将任意文档元素作为根

Python 使用XPath和Selenium将任意文档元素作为根,python,selenium,selenium-webdriver,dom,xpath,Python,Selenium,Selenium Webdriver,Dom,Xpath,Selenium的一个很好的特性是find_elements()和相关方法的范围可以限制在文档中的任何节点上。比如说, from selenium import webdriver from selenium.webdriver.common.by import By driver = webdriver.Chrome(executable_path = 'chromedriver.exe') driver.get("https://www.wikipedia.org/") driver.fi

Selenium的一个很好的特性是
find_elements()
和相关方法的范围可以限制在文档中的任何节点上。比如说,

from selenium import webdriver
from selenium.webdriver.common.by import By
driver = webdriver.Chrome(executable_path = 'chromedriver.exe')

driver.get("https://www.wikipedia.org/")
driver.find_elements(By.TAG_NAME, "div")
将返回文档中的所有
div
元素,但

footerElement = driver.find_element(By.CLASS_NAME, "footer")
footerElement.find_elements(By.TAG_NAME, "div")
将仅返回页脚中的
div
元素。在通过.XPATH查找具有
By.XPATH
的元素时,有没有获得类似功能的方法?我这样问是因为
footerElement.find_元素(By.XPATH,“//div”)
返回文档中的所有
div
元素,而不仅仅是页脚中的元素,这正是我希望它做的


需要说明的是:我知道如何构造XPath语句来只获取页脚中的
div
元素。但是我想知道是否可以从任意节点开始,比如上面示例中的
footerElement
,然后使用非常简单的语法,比如
footerElement.find_元素(By.XPATH,“//div”)
仅获取页脚中的
div
元素。

我可以使用
footer.find_元素(by.XPATH,“../div”)
这并不理想,但您可以随时编写
“//footer//div”
。谢谢,@AMC。这很接近,尽管我认为这种特殊的方法只适用于标记名为
footer
的元素。。
footer
是元素的类还是元素?感谢您提醒我可能会出现混淆。答案是:
footer
是位于的元素的类。在我文章的原始版本中,它也是WebElement类型的对象;此对象是由
footer=driver.find\u元素(by.CLASS\u NAME,“footer”)
创建的。但是为了避免混淆,我已经将这个对象从
footer
重命名为
footeelement
。我相信
“//div”
就足够了。这也是我的想法。但这还不够——请看我帖子中的“我问是因为…”这句话。如果我的评论模棱两可,很抱歉,我的意思是你可以使用
“//div”
,而不是
”//div”
,比如
footer.find_元素(By.XPATH,//div”)
。我明白了。但问题是
footer.find_元素(By.XPATH,“//div”)
匹配整个文档中的所有
div
元素,而不仅仅是嵌套在footer元素中的元素。哦,我的错误,我的假设是,既然您在footer元素上调用方法,它将被限制为该元素下的所有元素,而不是整个文件。