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

如何通过字典映射将城市名转为参数填充爬虫链接?

实现用城市名动态替换URL中的城市数字标识

你只需要从字典里根据传入的城市名取出对应数字,再替换到URL里的city:部分就行,同时建议处理城市名不存在的情况,避免请求错误链接。具体修改如下:

  1. 获取城市对应的数字ID:利用字典的get()方法,传入转小写后的城市名(避免大小写不匹配的问题),如果找不到对应城市可以返回提示或抛出异常。
  2. 动态拼接URL:把URL里的city:{city}替换成city:{city_id},用获取到的数字ID填充。
  3. 修正参数错误:你调用get_data("i", "charleston")时,page_index传了字符串"i",这会导致URL错误,应该传入数字类型的页码,比如1。

修改后的完整代码:

import requests
from bs4 import BeautifulSoup

def get_data(page_index, city):
    towns_dict = {"charleston": 8, "mount pleasant": 49, "john's island": 40, "folly beach": 22,"daniel island": 188, "james island": 37}
    
    # 转小写后获取城市ID,处理不存在的情况
    city_id = towns_dict.get(city.lower())
    if not city_id:
        print(f"未找到城市 {city} 对应的ID")
        return
    
    listings = []
    # 注意:如果要爬取1-21页,建议把URL中的page:{page_index}改为page:{i},避免重复请求同一页
    for i in range(1, 22):
        # 用city_id替换原来的city参数
        url = f'https://www.marshallwalker.com/listings/index/page:{page_index}/class:1/status:1,3,6/city:{city_id}/br:0/br_e:0/fba:0/fba_e:0/hba:0/hba_e:0#real-estate-listings'
        page = requests.get(url=url)

        soup = BeautifulSoup(page.content, 'html.parser')
        properties = soup.find_all('div', class_='summary-right')
        for prop in properties:
            address = prop.select('div.summary-right h3>a')[0].text
            price = prop.find('div', class_='s-price').text.replace("\t", "")
            location = prop.select('small.text-muted')[0].text
            details = prop.find_all("div", class_='s-cut s-common')
            details = details[1].text.strip()
            beds = details[:4]
            baths = details[6:-11]
            sqft = details[-9:]

            listings.append([address, location, price, beds, baths, sqft])
    print(listings)
    print()

# 调用时传入正确的页码数字和城市名
get_data(1, "charleston")

额外提醒:你代码里的循环是range(1,22),但URL里用的是传入的page_index,这可能和你的预期不符——如果是要爬取1到21页,应该把URL里的page:{page_index}改成page:{i},否则会重复请求同一页数据。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 18:45:33