如何用Selenium或BeautifulSoup4点击Div元素显示隐藏数据?
解决Selenium抓取隐藏手机号的问题
核心问题分析
你遇到的NoSuchElementException是因为用By.CLASS_NAME传入了多个类名——CLASS_NAME只支持单个类名,多类名组合会直接导致定位失败。
修正步骤与代码
1. 修正元素定位方式
改用By.CSS_SELECTOR定位多类名元素,或者选取单个唯一类名(比如js-show-phones),就能准确找到触发手机号显示的按钮。
2. 完整可运行代码
from selenium import webdriver from selenium.webdriver.chrome.service import Service from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC # 替换成你的chromedriver完整绝对路径,比如Linux下是/home/你的用户名/Downloads/chromedriver s = Service('/home/Downloads/chromedriver') driver = webdriver.Chrome(service=s) driver.get("https://bina.az/items/3141057") try: # 用显式等待替代time.sleep,更稳定地等待按钮可点击 show_phone_btn = WebDriverWait(driver, 10).until( EC.element_to_be_clickable((By.CSS_SELECTOR, ".show-phones.js-show-phones.active")) ) show_phone_btn.click() # 等待手机号元素加载完成后抓取 phone_numbers = WebDriverWait(driver, 10).until( EC.presence_of_all_elements_located((By.CLASS_NAME, "phone")) ) # 输出所有显示的手机号 for num in phone_numbers: print(num.text) finally: # 无论操作成功失败,都关闭浏览器 driver.quit()
额外注意事项
- 必须填写
chromedriver的完整绝对路径,避免因路径错误导致浏览器启动失败 - 显式等待
WebDriverWait比固定时长的time.sleep更可靠,能根据元素实际加载状态调整等待时间 - 点击按钮后一定要等待手机号元素出现再抓取,否则可能拿到空内容
内容的提问来源于stack exchange,提问作者Zekiyev
相关产品推荐
相关产品推荐

