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

如何用Python BeautifulSoup抓取弹窗按钮中的隐藏手机号

抓取haraj.com.sa隐藏手机号的可行方案

你当前用requests+BeautifulSoup的方式只能获取页面初始静态HTML,而目标手机号是点击「التواصل」按钮后通过JavaScript动态加载(可能是触发API请求或解密显示)的内容,静态请求无法拿到这部分数据。需要使用能模拟浏览器执行JS的工具来实现。

方案一:使用Selenium

步骤:

  1. 安装依赖:
pip install selenium

同时下载对应浏览器的驱动(比如ChromeDriver,需和你的Chrome版本匹配),并确保驱动路径可被Python找到。

  1. 示例代码:
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

url = "https://haraj.com.sa/1199808969"
headers = {'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/104.0.0.0 Safari/537.36.'}

# 配置Chrome选项
options = webdriver.ChromeOptions()
options.add_argument(f'user-agent={headers["User-Agent"]}')
# 可选:无头模式(不显示浏览器窗口)
# options.add_argument('--headless=new')

driver = webdriver.Chrome(options=options)
driver.get(url)

try:
    # 等待按钮出现并点击
    contact_btn = WebDriverWait(driver, 10).until(
        EC.element_to_be_clickable((By.CLASS_NAME, "contact"))
    )
    contact_btn.click()
    
    # 等待手机号元素加载完成并提取
    phone_element = WebDriverWait(driver, 10).until(
        EC.presence_of_element_located((By.CSS_SELECTOR, ".contact .phone"))
    )
    print("手机号:", phone_element.text)
finally:
    driver.quit()

方案二:使用Playwright(更简洁,无需手动管理驱动)

步骤:

  1. 安装依赖:
pip install playwright
playwright install chrome
  1. 示例代码:
from playwright.sync_api import sync_playwright

url = "https://haraj.com.sa/1199808969"
headers = {'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/104.0.0.0 Safari/537.36.'}

with sync_playwright() as p:
    browser = p.chromium.launch(headless=False)  # 设为True则无头模式
    context = browser.new_context(user_agent=headers["User-Agent"])
    page = context.new_page()
    page.goto(url)
    
    # 点击联系按钮
    page.locator(".contact button").click()
    
    # 等待手机号显示并提取
    phone = page.locator(".contact .phone").text_content(timeout=10000)
    print("手机号:", phone)
    
    browser.close()

补充说明:

  • 两种方案核心都是模拟浏览器行为,执行JavaScript代码,触发按钮点击后的动态加载过程,从而获取到隐藏的手机号。
  • 注意网站可能有反爬机制,建议添加合理的等待时间,避免频繁请求导致被封禁。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 12:36:25