我有一个网站,其中有一个按钮"显示更多",一个人可以点击喜欢的频率.在某种程度上,会有一个同名的<span>,一旦我看到那个,我就想停止点击这个按钮.

遗憾的是,当单击该按钮时,需要一些时间才能将所有内容展开并再次显示该按钮.在该时刻期间,标签"aria-busy="true"被设置.

因此,目前,我的代码可以工作,但我会等待10秒,直到再次按下按钮.这太长了,但当然,如果我将其设置得太低,操作可能会失败.

我当前的代码是:

# Params: url, button-class, span_label
waiting_time = 10
options = Options()
driver = webdriver.Chrome(options=options)
driver.get(url)
wait = WebDriverWait(driver, waiting_time)
button = wait.until(
    EC.element_to_be_clickable((By.CLASS_NAME, button-class))
)
while True:
    try:
        button.click()
        wait.until(EC.visibility_of_element_located((By.XPATH, span_label)))
        logging.debug("Found last block, continue")
        break  # Exit the loop if the span element is found
    except TimeoutException:
        continue  # Continue clicking the button if the span element is not found within the timeout

content = driver.page_source
driver.quit()

我已经用过WebDriverWait了,但那个不做隐式等待.此外,我有一种感觉,这种循环方法相当糟糕.

所以我的问题是:有没有更高效、更好的代码来点击按钮,直到跨度出现?

推荐答案

要继续单击显示更多按钮直到<span>出现,您可以为<span>中的invisibility_of_element_located()创建WebDriverWait,然后为element_to_be_clickable()创建WebDriverWait,如下所示:

while True:
    try:
        wait.until(EC.invisibility_of_element_located((By.XPATH, span_label)))
        wait.until(EC.element_to_be_clickable((By.CLASS_NAME, button-class)).click()
        continue # Continue clicking the button if the span element is not found within the timeout
    except TimeoutException:
        logging.debug("Found the span, break")
        break

content = driver.page_source
driver.quit()

Note:您必须添加以下导入:

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC

Python-3.x相关问答推荐

TypeError:&Quot;Value&Quot;参数必须是标量、Dict或Series,但您传递了&Quot;Index&Quot;

当索引大于一个整数而小于前一个索引时,我如何返回列值?

如何使用正则表达式通过反向搜索从链接中获取特定文本

对大型数据框中的选定列进行重新排序

为什么 get_form 方法中小部件的更改没有反映 Django 管理站点中的更改

从一列字符串中提取子字符串并将它们放入列表中

如何通过 python 使用 auth no priv 获取 SNMPv3?

如何统计一个值连续出现的次数?

如何确保 GCP Document AI 模型输出与输入文件同名的 JSON?

列出相同索引的Pandas

spaCy 中的匹配模式返回空结果

BeautifulSoup 和 pd.read_html - 如何将链接保存到最终数据框中的单独列中?

python中两个连续的yield语句如何工作?

获取嵌套字典的所有键

pythondecorator中的变量范围

判断对 python 3 支持的要求

混合全局/参数和名为top的函数的奇怪python行为

plt.cm.get_cmap 中可以使用哪些名称?

如何在 QGraphicsView 中启用平移和zoom

Django 教程 unicode 不起作用