首页 > 编程问答 >如何使用新版本抓取foursquare?

如何使用新版本抓取foursquare?

时间:2024-08-06 15:25:16浏览次数:6  
标签:python web-scraping

我正在尝试使用此代码从 foursquare 中抓取场地

def getNearbyVenues(names, latitudes, longitudes, radius=500):
    
    venues_list=[]
    for name, lat, lng in zip(names, latitudes, longitudes):
        print(name)
            
        # Create the API request URL
        url = 'https://api.foursquare.com/v3/places/nearby&client_id={}&client_secret={}&v={}&ll={},{}&radius={}&limit={}'.format(
            CLIENT_ID, 
            CLIENT_SECRET, 
            VERSION, 
            lat, 
            lng, 
            radius, 
            LIMIT)
            
        # Make the GET request
        results = requests.get(url).json()["response"]['groups'][0]['items']
        
        # Return only relevant information for each nearby venue
        venues_list.append([(
            name, 
            lat, 
            lng, 
            v['venue']['name'], 
            v['venue']['location']['lat'], 
            v['venue']['location']['lng'],  
            v['venue']['categories'][0]['name']) for v in results])

    nearby_venues = pd.DataFrame([item for venue_list in venues_list for item in venue_list])
    nearby_venues.columns = ['Neighborhood', 
                  'Neighborhood Latitude', 
                  'Neighborhood Longitude', 
                  'Venue', 
                  'Venue Latitude', 
                  'Venue Longitude', 
                  'Venue Category']
    
    return(nearby_venues)

但我收到此错误

{
    "meta": {
        "code": 410,
        "errorType": "deprecated",
        "errorDetail": "Usage of the V2 Places API has been deprecated for new Projects. Please see our updated documentation for V3 for more details: https://docs.foursquare.com/reference",
        "requestId": "619928ff498a047e3a81f23a"
    },
    "response": {}
}

我应该在代码中编辑什么才能使其正常工作

我无法从此链接中弄清楚| ||https://developer.foursquare.com/reference/place-search 更新

使用@Corralien的解决方案: 这是 results.json() 的结果 我正在尝试获取地点地点纬度地点经度地点类别我必须编写更多内容,所以我的代码主要不是代码

This the result of results.json() I'm trying to get Venue Venue Latitude Venue Longitude Venue Category I have to write more so my code is not mostly code

  'timezone': 'Europe/Helsinki'},
  {'fsq_id': '4adcdb23f964a520c76021e3',
   'categories': [{'id': 10031,
     'name': 'Science Museum',
     'icon': {'prefix': 'https://ss3.4sqi.net/img/categories_v2/arts_entertainment/museum_science_',
      'suffix': '.png'}}],
   'chains': [],
   'distance': 148,
   'geocodes': {'main': {'latitude': 60.171349882576,
     'longitude': 24.93154852286545}},
   'location': {'address': 'Pohjoinen Rautatiekatu 13',
    'country': 'FI',
    'cross_street': 'Arkadiankatu / Nervanderinkatu',
    'locality': 'Helsinki',
    'neighborhood': ['Etu-Töölö'],
    'postcode': '00100',

提供的错误消息表明正在尝试使用 Foursquare Places API 的 V2 版本,该版本已被弃用。需要更新代码以使用 V3 版本。

以下是更新代码以使用 Foursquare Places API V3 的方法:

```python import requests import pandas as pd

CLIENT_ID = 'YOUR_CLIENT_ID' CLIENT_SECRET = 'YOUR_CLIENT_SECRET' VERSION = '20230801' LIMIT = 50

def getNearbyVenues(names, latitudes, longitudes, radius=500):

 venues_list=[]
 for name, lat, lng in zip(names, latitudes, longitudes):
     print(name)

     # 创建 API 请求 URL
     url = f'https://api.foursquare.com/v3/places/search?ll={lat},{lng}&radius={radius}&limit={LIMIT}'

     # 设置请求头
     headers = {
         "Accept": "application/json",
         "Authorization": f"Bearer {YOUR_API_KEY}"
     }

     # 发出 GET 请求
     response = requests.get(url, headers=headers)

     # 检查请求是否成功
     if response.status_code == 200:
         results = response.json()
     else:
         raise Exception(f"请求失败,状态码:{response.status_code}")

     # 提取相关信息
     for result in results['results']:
         venue = {
             'Neighborhood': name,
             'Neighborhood Latitude': lat,
             'Neighborhood Longitude': lng,
             'Venue': result['name'],
             'Venue Latitude': result['geocodes']['main']['latitude'],
             'Venue Longitude': result['geocodes']['main']['longitude'],
             'Venue Category': result['categories'][0]['name'] if result['categories'] else None
         }
         venues_list.append(venue)

 nearby_venues = pd.DataFrame(venues_list)
 return(nearby_venues)

```

更改说明:

  1. API 端点: 将 API 端点更新为 https://api.foursquare.com/v3/places/search
  2. API 密钥: 使用的实际 API 密钥替换 YOUR_API_KEY
  3. 参数: 更新参数以匹配 V3 API。删除了 client_id client_secret ,并添加了 Authorization 标头,其中包含的 API 密钥。
  4. 响应处理: 根据 V3 API 响应结构更新了结果提取逻辑。

使用代码:

  1. 替换占位符: YOUR_API_KEY 替换为的实际 Foursquare API 密钥。
  2. 提供数据: names latitudes longitudes 变量替换为的实际数据列表。

此代码将返回一个 Pandas DataFrame,其中包含请求的每个位置附近的场馆列表,以及它们的名称、纬度、经度和类别。

请记住查看 Foursquare Places API V3 文档以获取有关可用端点、参数和响应格式的更多详细信息:

希望这有帮助!如果有任何其他问题,请告诉我。

标签:python,web-scraping
From: 70904066

相关文章

  • Python 卡在第 1 页
    让它读取下一页结果的最佳方法是什么?目前正在拉取数据,但只有第1页importrequestsimportjsonpage=1url="https://api-prod.grip.events/1/container/4368/search?search=&sort=name&order=asc&type_id=4907,4906,5265,4964,4904,1026,4908&page=%d"headers={......
  • 无法反序列化解码 JWT python 时的关键数据
    我正在使用pyjwt库来解码JWT令牌。我在解码时遇到此错误。代码在文档中给出。importjwtencoded_jwt='''eyJ0eXAiOiJKV1QiLCJhbG......'''secret=b''''-----BEGINPUBLICKEY-----MIIFRjCCBC6gAwIBAgIQCIdSGhpikQCjOIY154XoqzANBgkqhkiG9......
  • Python科研武器库 - 字符串操作 - 字符串开头结尾判断 startswith() endswith()
    使用场景:按照开头的前缀、结尾的后缀来判断、筛选目标字符串。使用函数:str.startswith(search_string,start,end)str.endswith(search_string,start,end)search_string:要匹配的目标字符串。start:要从中匹配search_string的str的起始索引。end:要考虑匹配的str的结......
  • 我正在 python 中使用 aspose.pdf 将 pdf 转换为 excel 。但问题是它只能将 pdf 的前
    `从tkinter导入*将aspose.pdf导入为ap从tkinter导入文件对话框importpandasaspdinput_pdf=filedialog.askopenfilename(filetypes=(("PDF文件",".pdf"),("所有文件",".")))output_file=filedialog.asksaveasfil......
  • 如何在selenium python中访问电子邮件中的所有文件夹
    我使用imaplib库,但有时无法访问某些帐户,我使用poplib但它只支持访问主邮箱,但不支持访问其他文件夹,如垃圾邮件我想使用imaplib,但不会出现有时甚至无法访问的错误尽管我有一个帐户,但我仍然可以访问它,或者是否有另一个库可以快速支持该帐户?你想要使用Selenium和Python......
  • python安装torch-cluster、torch-scatter、torch-sparse和torch-geometric | torch_ge
    1.检查CUDA版本【方法1】用nvidia-smi已装cuda,用nvidia-smi或nvcc-V查看【方法2】用torch已装torch,用torch代码打印importtorchprint(torch.__version__)#查看pytorch安装的版本号print(torch.cuda.is_available())#查看cuda是否可......
  • Python:学生成绩管理系统(大学编程期末实验)
    引言在这个信息时代,教育管理的自动化已成为提高效率的关键。本文将介绍如何使用Python开发一个学生成绩管理系统,旨在简化成绩记录、查询和分析的过程。创作灵感来源本项目灵感来源于我在教育机构的工作经历,以及对提高教育管理效率的持续追求。通过复盘过往项目,我意识到一个......
  • 手把手教你使用Python网络爬虫下载一本小说(附源码)
    大家好,我是Python进阶者。前言前几天【磐奚鸟】大佬在群里分享了一个抓取小说的代码,感觉还是蛮不错的,这里分享给大家学习。一、小说下载如果你想下载该网站上的任意一本小说的话,直接点击链接进去,如下图所示。只要将URL中的这个数字拿到就可以了,比方说这里是951,那么这个数字......
  • 借助 Transformer 实现美股价格的预测(Python干货)
    作者:老余捞鱼原创不易,转载请标明出处及原作者。写在前面的话:      Transformer是一种在自然语言处理等领域广泛应用的深度学习架构,与传统的循环神经网络(RNN)相比,Transformer可以并行处理输入序列的各个位置,大大提高了计算效率。而且通过多层的深度堆叠,能够学习......
  • 将 Mojo 与 Python 结合使用
    Mojo允许您访问整个Python生态系统,但环境可能会因Python的安装方式而异。花些时间准确了解Python中的模块和包的工作原理是值得的,因为有一些复杂情况需要注意。如果您以前在调用Python代码时遇到困难,这将帮助您入门。Python中的模块和包让我们从Python开始,如......