python - 如何使用 python selenium 单击带有文本 bb1 的元素
问题描述
<yt-formatted-string id="channel-title" class="style-scope ytd-account-item-renderer">bb1</yt-formatted-string>
低于一个是完整 x 路径的危险查找元素,因为索引可能会更改
self.driver.find_element_by_xpath('/html/body/ytd-app/ytd-popup-container/iron-dropdown/div/ytd-multi-page-menu-renderer/div[4]/ytd-multi-page-menu-renderer/div[3]/div[1]/ytd-account-section-list-renderer[1]/div/ytd-account-item-section-renderer/div/ytd-account-item-renderer[4]/paper-icon-item/paper-item-body/yt-formatted-string[1]').click()
解决方案
要单击文本为bb1的元素,您可以使用以下任一Locator Strategies:
使用
css_selector
:self.driver.find_element_by_css_selector("yt-formatted-string.style-scope.ytd-account-item-renderer#channel-title").click()
使用
xpath
:self.driver.find_element_by_xpath("//yt-formatted-string[@class='style-scope ytd-account-item-renderer' and @id='channel-title'][text()='bb1']").click()
理想情况下,要单击需要诱导WebDriverWait的元素element_to_be_clickable()
,您可以使用以下任一Locator Strategies:
使用
CSS_SELECTOR
:WebDriverWait(self.driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "yt-formatted-string.style-scope.ytd-account-item-renderer#channel-title"))).click()
使用
XPATH
:WebDriverWait(self.driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//yt-formatted-string[@class='style-scope ytd-account-item-renderer' and @id='channel-title'][text()='bb1']"))).click()
注意:您必须添加以下导入:
from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC
参考
您可以在以下位置找到一些相关的详细讨论:
推荐阅读
- r - 在 dplyr mutate 工作流程中引用和索引其他数据帧
- php - Laravel Ajax 请求,没有“Access-Control-Allow-Origin”标头
- javascript - 如何在 keydown 上启动计时器并在 keyup 上停止?
- memory-management - 如何在不初始化的情况下在 Windows 中分配 RAM 页面?
- reactjs - 组件之间的 React 过渡组动画(淡入组件代替另一个)
- android - 模拟器 Android 15 - 黑屏
- amazon-web-services - 您可以使用基于 AWS Route 53 延迟的路由来解析 AWS 之外的服务器吗?
- r - 如何检查 r 中数据框中的列的值是否对应于数据框每一行的另一列的单次出现?
- docker - windows/amd64 没有匹配的清单
- ruby-on-rails - 尝试诊断 ActiveRecord::ConcurrentMigrationError 时缺少 pg_locks 和 pg_stat_activity 表