You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Selenium点击「Show phone number」按钮后手机号不显示问题求助

Selenium点击「Show phone number」后手机号不显示的解决办法

1. 隐藏自动化特征,规避网站检测

多数网站会识别Selenium的自动化标识,限制核心交互逻辑。给Firefox添加参数并修改浏览器属性:

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

driver_path = r"C:\Program Files\Mozilla Firefox\firefox.exe"

options = webdriver.FirefoxOptions()
options.binary_location = driver_path
# 禁用自动化检测相关特征
options.add_argument("--disable-blink-features=AutomationControlled")
options.add_experimental_option("excludeSwitches", ["enable-automation"])
options.add_experimental_option('useAutomationExtension', False)

driver = webdriver.Firefox(options=options)
# 修改navigator.webdriver属性,伪装成普通浏览器
driver.execute_script("Object.defineProperty(navigator, 'webdriver', {get: () => undefined})")

url = "https://www.dubizzle.com.eg/en/ad/198522215"
driver.get(url)

2. 修正元素等待条件与定位逻辑

  • 原代码用presence_of_element_located仅确认元素存在,改为element_to_be_clickable确保按钮处于可交互状态
  • 放弃依赖动态生成的长串class名,改用更稳定的XPATH定位手机号元素

修改后的交互代码:

try:
    # 先处理Cookie同意弹窗(若页面存在)
    cookie_btn = WebDriverWait(driver, 10).until(
        EC.element_to_be_clickable((By.XPATH, "//button[contains(text(), 'Accept')]"))
    )
    cookie_btn.click()
except:
    pass  # 无弹窗则跳过

# 等待并点击「Show phone number」按钮
button = WebDriverWait(driver, 20).until(
    EC.element_to_be_clickable((By.XPATH, "//span[text()='Show phone number']/ancestor::button"))
)
button.click()

# 等待手机号显示并获取文本(基于按钮的兄弟元素定位,更稳定)
phone_number = WebDriverWait(driver, 10).until(
    EC.visibility_of_element_located((By.XPATH, "//button[.//span[text()='Show phone number']]/following-sibling::span"))
).text

print("Phone number:", phone_number)
finally:
    driver.quit()

3. 额外注意事项

  • 不要设置过长等待时间(原代码2000秒无意义,合理范围为10-20秒)
  • 若网站反爬严格,可在点击前后添加1-2秒随机延迟(需导入time模块)
  • 定期检查XPATH有效性,网站更新后可能需要调整定位规则

内容的提问来源于stack exchange,提问作者Abdelrahman

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.29 10:52:11