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

使用Requests与BeautifulSoup爬取网页时无法提取邮箱的解决办法咨询

解决KW房产代理页面邮箱提取问题

常见原因与对应方案

1. 识别Cloudflare邮箱加密(最可能的情况)

你看到的加密路径大概率是Cloudflare的邮箱保护机制,格式通常是/cdn-cgi/l/email-protection#xxxxxx。这种加密可以通过异或算法解密,步骤如下:

  • 从页面中提取加密字符串(即#后的部分)
  • 用以下Python函数解密:
def decode_cf_email(encoded_str):
    key = int(encoded_str[:2], 16)
    return ''.join([chr(int(encoded_str[i:i+2], 16) ^ key) for i in range(2, len(encoded_str), 2)])
  • 示例使用:
from bs4 import BeautifulSoup
import requests

response = requests.get("https://www.kw.com/agent/UPA-6587385179144187908-1")
soup = BeautifulSoup(response.text, 'html.parser')
# 定位包含加密邮箱的链接(需根据页面实际结构调整选择器)
email_link = soup.find('a', href=lambda x: x and 'cdn-cgi/l/email-protection' in x)['href']
# 提取#后的加密串
encoded_part = email_link.split('#')[1]
real_email = decode_cf_email(encoded_part)
print(real_email)

2. 模拟浏览器渲染动态内容

如果邮箱是通过JavaScript动态生成的(比如页面加载后通过AJAX获取),Requests+BeautifulSoup无法直接获取,需要用Selenium或Playwright模拟浏览器:

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.options import Options

# 无头模式运行,避免弹出浏览器窗口
options = Options()
options.add_argument("--headless=new")
driver = webdriver.Chrome(options=options)

driver.get("https://www.kw.com/agent/UPA-6587385179144187908-1")
# 等待页面完全渲染(可根据实际情况调整等待时间)
driver.implicitly_wait(5)

# 定位邮箱元素(需根据页面实际结构调整选择器)
email_element = driver.find_element(By.CSS_SELECTOR, "a[href*='cdn-cgi/l/email-protection']")
# 获取解密后的邮箱文本
real_email = email_element.text

driver.quit()
print(real_email)

3. 直接调用后端API接口

打开浏览器开发者工具(F12),切换到Network标签,刷新页面后筛选XHR/fetch请求,查看是否有返回代理详细信息(包含邮箱)的API接口。找到后直接请求该接口,解析JSON数据即可获取邮箱,这种方式比爬页面更高效稳定。

示例代码:

import requests

# 替换为实际找到的API接口地址
api_url = "https://www.kw.com/api/agent/detail/UPA-6587385179144187908-1"
headers = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36"
}
response = requests.get(api_url, headers=headers)
data = response.json()
real_email = data.get("agent", {}).get("email")
print(real_email)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 21:30:13