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

如何用BeautifulSoup提取页面中含/pl/oferta/的所有链接?

修复后的Python爬虫代码(提取Otodom房源链接)

原代码的问题点

  • 变量名错误:定义了houses_listings却打印未定义的job_listings,触发NameError
  • 未添加请求头,易被网站反爬机制拦截,返回空页面
  • 硬编码的CSS类名可能已失效,导致无法匹配元素
  • 未实现多页爬取逻辑(原代码注释了循环)

可用功能代码

import requests
from bs4 import BeautifulSoup

# 构造目标URL模板
base_url = "https://www.otodom.pl/pl/oferty/sprzedaz/mieszkanie/wiele-lokalizacji?distanceRadius=0&page={}&limit=36&locations=%5Bregions-1%2Cregions-11%2Cregions-12%2Cregions-13%2Cregions-2%2Cregions-5%2Cregions-10%2Cregions-9%2Cregions-8%2Cregions-7%2Cregions-4%2Cregions-6%2Cregions-3%2Cregions-14%2Cregions-15%2Cregions-16%5D&by=DEFAULT&direction=DESC&viewType=listing"

# 请求头,模拟浏览器访问
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"
}

page_num = 1
all_links = set()  # 用集合去重

while True:
    print(f"正在爬取第 {page_num} 页...")
    current_url = base_url.format(page_num)
    
    try:
        response = requests.get(current_url, headers=headers)
        response.raise_for_status()  # 检查请求是否成功
        soup = BeautifulSoup(response.text, "html.parser")
        
        # 查找所有href包含"/pl/oferta/"的a标签,不依赖类名更稳定
        listings = soup.find_all("a", href=lambda x: x and "/pl/oferta/" in x)
        
        if not listings:
            print("未找到更多房源链接,停止爬取")
            break
        
        # 提取完整链接并添加到集合
        for item in listings:
            link = "https://www.otodom.pl" + item["href"] if item["href"].startswith("/") else item["href"]
            all_links.add(link)
        
        page_num += 1
        
    except Exception as e:
        print(f"爬取第 {page_num} 页时出错: {str(e)}")
        break

# 打印结果
print(f"\n共提取到 {len(all_links)} 条唯一房源链接:")
for link in all_links:
    print(link)

代码说明

  1. 请求头设置:添加User-Agent模拟浏览器,避免被网站识别为爬虫
  2. 链接提取逻辑:通过href关键词匹配,不依赖易变的CSS类名,提升稳定性
  3. 多页处理:循环爬取直到没有新链接,自动终止
  4. 去重处理:使用集合存储链接,避免重复
  5. 异常处理:捕获请求错误,防止程序崩溃

内容的提问来源于stack exchange,提问作者Paweł Paprzycki

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 14:17:23