python - Selenium find_elements By.XPATH 试图提取 href urls 错误
问题描述
使用 Firefox 网络驱动程序,我想从中提取所有a href
包含单词的 URL。我正在使用最新的硒二进制文件。试过这个:
driver = webdriver.Firefox()
driver.get(url)
nodes = driver.find_elements(By.XPATH, "//a[contains(@href,'products')]/@href")
print("nodes: ", nodes)
links = []
for elem in nodes:
links.append(elem)
但得到一个类型错误:
selenium.common.exceptions.WebDriverException: Message: TypeError: Expected an element or WindowProxy, got: [object Attr href="https://www.example.com/catalogue/products/a.html"]
也尝试过driver.find_elements(By.XPATH, "//a[contains(@href,'products')]")
,然后getAttribute("href")
为每一个使用,但也不能。
不明白错误在哪里以及如何解决。
html的摘录:
<html>
<body>
<ul class="level2-megamenu">
<li>
<div class="level1-title">
<a href="https://www.example.com/catalogue/products/a.html">
<strong style="color:#828282;font-size:>Text</strong>
</a>
</div>
</li>
</ul>
</body>
</html>
解决方案
要使用Selenium和python提取href
属性,您必须诱导WebDriverWait并且您可以使用以下任一Locator Strategies:visibility_of_all_elements_located()
使用
CSS_SELECTOR
:print([my_elem.get_attribute("href") for my_elem in WebDriverWait(driver, 20).until(EC.visibility_of_all_elements_located((By.CSS_SELECTOR, "a[href*='products']")))])
使用
XPATH
:print([my_elem.get_attribute("href") for my_elem in WebDriverWait(driver, 20).until(EC.visibility_of_all_elements_located((By.XPATH, "//a[contains(@href,'products')]")))])
注意:您必须添加以下导入:
from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC
推荐阅读
- azure - 逻辑上独立的 azure kubernetes 部署
- canvas - Fabric JS 层,一层带控件
- oracle - 为什么在远程数据库中忽略 dml 错误日志记录
- pentaho - 如何在 Pentaho 中迁移 blob 数据类型
- android - Android Navigation Component 更改 backstack
- amazon-web-services - Terraform 模块抛出错误“文字未终止”
- sql - 从表 A 的过滤部分中选择行,其中列与表 B 中按 ID 匹配的行中的列匹配关系
- aws-sam-cli - 从 Python 脚本中运行 AWS SAM 构建
- oracle - 如何使用oracle sql将货币金额检索为单词
- regex - 如何从字符串中间删除空格但在开头保留空格?