Selenium未点击页面上的所有按钮

0 投票
1 回答
21 浏览
提问于 2025-04-13 15:40

我正在抓取这个页面:https://www.immobilienscout24.de/Suche/de/berlin/berlin/wohnung-kaufen

这个页面上有多个公寓被放在一起显示,就像图片中所示。我想点击那个按钮(用红色椭圆圈起来的)来显示这个组合中的所有公寓。在这里输入图片描述

我的代码可以展开第一个组合,但不能展开其他的(有些页面可能只有1个、5个或者一个都没有)。我用的代码如下:

while True:
        try:
            show_more_units = driver.find_element(By.XPATH, '//*[@id="result-p-149498364"]/div[3]/button')
            show_more_units.click()
            time.sleep(0.2)
            print("Show more button clicked.")

        except:
            print('No button to "Show more".')
            break

我发现每个组合按钮的ID都不一样。我也尝试了以下方法:

show_more_units = driver.find_element(By.XPATH, "//button[contains(text(), 'Einheiten anzeigen')]")

还有

show_more_units = driver.find_element(By.CLASS_NAME, 'padding-left-none link-text-secondary button')

但这些方法都没有用。实际上,这两种方法甚至连一个组合都无法展开。

我希望我的代码能在抓取我需要的信息之前,先展开所有的组合。我该怎么做呢?

提前谢谢你。

附注:按钮的HTML代码如下:

<button class="padding-left-none link-text-secondary button"><span class="s24-icons-s24_chevron_right_24"></span> <!-- -->3 weitere Einheiten anzeigen</button>

1 个回答

1

你做得已经很接近了。我改了一些地方让它能正常工作:

  1. 使用了不同的定位方式。这个 CSS 选择器 article button.button 只匹配你想要的按钮。

  2. 添加了一个 WebDriverWait,确保每次点击按钮时它都是准备好的。

  3. 我的 try-except 主要是捕捉 WebDriverWait 超时的 TimeoutException。这种情况应该只会在所有匹配的按钮都被点击并从页面上移除后发生。

    from selenium import webdriver
    from selenium.common.exceptions import TimeoutException
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support import expected_conditions as EC
    from selenium.webdriver.support.wait import WebDriverWait
    
    url = 'https://www.immobilienscout24.de/Suche/de/berlin/berlin/wohnung-kaufen'
    driver = webdriver.Chrome()
    driver.maximize_window()
    driver.get(url)
    wait = WebDriverWait(driver, 5)
    while True:
        try:
           wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR,"article button.button"))).click()
    
        except TimeoutException:
            break
    
    driver.quit()
    

补充说明:

  1. 最好只捕捉你打算处理的异常。捕捉太多异常可能会导致隐藏的错误,这样调查起来会更困难。
  2. 在与任何元素互动之前,应该始终使用 WebDriverWait。这样可以确保元素已经准备好,减少偶发(有时是确定性的)错误。
  3. 除非绝对必要,否则尽量避免使用 time.sleep()。这样可以让你的脚本运行得更快,减少出错的可能性,见上面的第2点。
  4. 你最后的定位尝试 (By.CLASS_NAME, 'padding-left-none link-text-secondary button') 使用 By.CLASS_NAME 的方式不对。它只期望一个类名,而你给了它三个。要么只选择其中一个类,要么改成 By.CSS_SELECTOR,比如 .padding-left-none.link-text-secondary.button

撰写回答