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

如何使用BeautifulSoup选中多层嵌套结构内的指定div元素?

多层嵌套div目标元素抓取失败的调整方案

问题原因

问题主要来自两个方面:

  1. 元素选择API用法错误:select_one 方法仅接收CSS选择器字符串作为参数,你当前传入的name、class_是find系列方法的参数,匹配规则无法生效。
  2. 反爬与动态渲染拦截:Zillow站点有严格的反爬机制,直接通过requests.get发起的请求会被识别为爬虫,返回的页面没有完整的动态渲染房源数据,自然找不到目标类名的div。

调整步骤

1. 修正元素选择写法

两种可选的正确写法:

  • 保留select_one,传入CSS选择器:
price_tag = soup.select_one('div.list-card-price')
  • 改用find方法匹配标签和类名:
price_tag = soup.find(name='div', class_="list-card-price")

2. 解决反爬与动态内容加载问题

第一步:添加请求头模拟浏览器

给requests请求添加合法的User-Agent,避免被直接识别为爬虫:

from bs4 import BeautifulSoup
import requests
import lxml

headers = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"
}
response = requests.get(url="https://www.zillow.com/homes/for_rent/1-_beds/?.....", headers=headers)
data = response.text
# 可先打印源码确认是否存在目标类名
# print(data)
soup = BeautifulSoup(data,"lxml")
price_tag = soup.select_one('div.list-card-price')
print(price_tag)

第二步:动态渲染场景适配

如果添加请求头后仍然找不到目标元素,说明房源数据是前端JS动态加载的,静态请求无法获取,改用模拟浏览器加载的方案即可,示例使用Selenium:

from bs4 import BeautifulSoup
from selenium import webdriver
from selenium.webdriver.chrome.options import Options

# 配置浏览器参数
chrome_options = Options()
chrome_options.add_argument("--headless=new") # 无头模式,不弹出浏览器窗口
chrome_options.add_argument("user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36")

driver = webdriver.Chrome(options=chrome_options)
driver.get("https://www.zillow.com/homes/for_rent/1-_beds/?.....")
# 等待页面动态加载完成
driver.implicitly_wait(10)
# 获取渲染后的完整页面源码
full_page = driver.page_source
soup = BeautifulSoup(full_page, "lxml")
price_tag = soup.select_one('div.list-card-price')
print(price_tag.text if price_tag else "未匹配到目标元素")
# 关闭浏览器
driver.quit()

注意:Zillow反爬策略严格,频繁请求可能会被封禁IP,建议控制请求间隔,必要时搭配代理池使用

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 20:15:05