python - Selenium 在 Webelement 中通过 xpath 查找
问题描述
我有这个页面:
<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 开始 whit dot . ): 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 - 使用 strptime 的日期转换跳过 UTC 部分
- python - 如何在networkx中使用python随机排列图的节点?
- javascript - 有什么方法可以在 reactjs 的 Link 标签中使用 target="_blank"
- node.js - 更新的 Create-React-App 不再构建
- c# - 错误:VS2019 在创建 .NET CORE 2.1 Web 应用程序后抛出 2 个错误
- kubernetes - 如何以 HTTPS 方式访问 Kubernetes 外部 IP
- spring-boot - Mockito 模拟 CassandraOperation Slice 方法
- sql-server - 插入到另一个数据库后的 SQL Server 触发器未触发
- javascript - Javascript 动作总是拉第一个表
- encryption - 如果 IV 每次都更改,则重用密钥