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

Python数据爬取疑问:如何获取指定class的div中的经纬度值

解决方案

你需要在定位到目标section后,进一步筛选出class为text-xs mt-2的div标签,而不是直接提取整个section的文本。修改后的代码如下:

map_tags = web_bs4.find_all("section", {"class": "relative mb-8 max-md:mb-8"})
if len(map_tags) >= 3:
    map_tag = map_tags[2]
    # 定位到目标div标签
    target_div = map_tag.find("div", class_="text-xs mt-2")
    # 判断是否找到该div,存在则提取文本,否则返回"-"
    map = target_div.get_text().replace("\n", "") if target_div else "-"
else:
    map = "-"

关键说明:

  • 使用find()方法在已定位的section标签内,精准查找class为text-xs mt-2的div(class_是BeautifulSoup中用于指定class的参数,避免和Python关键字class冲突)。
  • 增加了对target_div是否存在的判断,防止因标签不存在导致报错。
  • 提取文本时保留你原有的换行符替换操作,保证输出格式整洁。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 21:28:09