python - 在 Webelement 中通过 xpath 查找 Selenium

标签 python selenium xpath selenium-chromedriver

我有这个页面:

<html>
<head>
    <title>Document Example</title>
</head>
<body>
    <div id="container">
        <div class="section">
            <h1>Section 1</h1>
            <li class="links">
                <ul><a href="link.com/1"></a></ul>
                <ul><a href="link.com/2"></a></ul>
                <ul><a href="link.com/3"></a></ul>
            </li>
        </div>
        <div class="section">
            <h1>Section 2</h1>
            <li class="links">
                <ul><a href="link.com/4"></a></ul>
                <ul><a href="link.com/5"></a></ul>
                <ul><a href="link.com/6"></a></ul>
            </li>
        </div>
        <div class="section">
            <h1>Section 3</h1>
            <li class="links">
                <ul><a href="link.com/7"></a></ul>
                <ul><a href="link.com/8"></a></ul>
                <ul><a href="link.com/9"></a></ul>
            </li>
        </div>
    </div>
</body>
</html>

我想按部分分组链接:

driver.get("mypage.com")

sections = driver.find_elements_by_xpath("//div[@class='section']")
for section in sections:
    section_name = section.find_element_by_xpath("//h1[@class='name']").get_attribute('innerHTML') #This fails

    links = section.find_elements_by_xpath("//ul/a") #This find all links in page, not only links in section

问题是,我通过 xpath 在所有页面中找到了一个元素列表 (WebElement),现在我想通过 xpath 找到元素部分内的所有特定元素,而不是在所有页面中。

怎么了?

编辑 1

这解决了问题(现在 xpath 以点 . 开头): driver.get("mypage.com")

sections = driver.find_elements_by_xpath("//div[@class='section']")
for section in sections:
    section_name = section.find_element_by_xpath(".//h1[@class='name']").get_attribute('innerHTML') #This fails

    links = section.find_elements_by_xpath(".//ul/a") #This find all links in page, not only links in section

这里是你找到的解释:http://selenium-python.readthedocs.io/api.html#selenium.webdriver.remote.webelement.WebElement.find_element_by_xpath

最佳答案

可能有用

sections = driver.find_elements_by_xpath("//div[@class='section']")
for i, section in enumerate(sections):
    section_name = section.text
    links = section.find_elements_by_xpath("//div[@class='section'][%s]//a" % str(i+1))

关于python - 在 Webelement 中通过 xpath 查找 Selenium,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50977255/

相关文章:

python - 在 jython 2.1 中运行外部命令并控制输入/输出

selenium - TestNG配置失败

xslt - 使用XSLT添加必需节点

Python 在相互依赖的类实例中使用 setter

python / Selenium : How to set "value" for input when it is not listed in page source?

java - Selenium-根据文本匹配获取列表索引号

c# - 通过 XPath 使用 HtmlAgilityPack 从 html 文档获取文本

javascript - 从 HTML 表获取 href 链接的策略

Python - 计算文本文件中的空白行

java - Cucumber Scenario Outline 上的 Example 表是否可以有空值?