Cloud Function无法向PubSub Topic发布消息返回404,正确代码如何编写?
问题根因
- 现有代码仅打印了爬取到的数据,根本没有调用PubSub的消息发布接口,因此PubSub Topic不会收到任何消息
- PubSub返回404通常由三个原因导致:项目ID填写错误、Topic名称拼写不匹配、Cloud Function运行身份缺少PubSub发布权限
修复方案
代码修正
你可以直接使用以下修改后的代码,替换原有逻辑即可:
import base64 import json from bs4 import BeautifulSoup import requests from google.cloud import pubsub_v1 def hello_pubsub(event, context): publisher = pubsub_v1.PublisherClient() # 请确认此处项目ID和Topic名称和你实际创建的完全一致 topic_path = publisher.topic_path("tokyo-ring-<secret>", "webscraping") html_text = requests.get('https://www.arabam.com/ikinci-el?take=50').text soup = BeautifulSoup(html_text,'lxml') models = soup.find_all('tr', class_='listing-list-item pr should-hover bg-white') for model in models: model_name = model.find('td', class_='listing-modelname pr').text.strip() title = model.find('td', class_='horizontal-half-padder-minus pr').text.strip() model_year = model.find('td', class_='listing-text pl8 pr8 tac pr').text.strip() price = model.find('td', 'pl8 pr8 tac pr').text.replace('TL','').replace(' ','').replace('.','').strip() publish_date = model.find('td', class_='listing-text tac pr').text.strip() location = model.find('div', style='display:flex;justify-content:center;align-items:center;height:81px').text.split(' ', 1)[0].strip() # 用json.dumps构造JSON,避免手动拼接的转义错误 data_dict = { "model_name": model_name, "title": title, "model_year": model_year, "price": price, "publish_date": publish_date, "location": location } data_str = json.dumps(data_dict, ensure_ascii=False) # PubSub要求消息为字节类型,所以需要编码 data_bytes = data_str.encode("utf-8") # 实际发布消息 future = publisher.publish(topic_path, data_bytes) # 等待发布完成,防止函数提前退出导致消息丢失 future.result() print(f"已成功发布消息:{data_str}")
权限与配置验证
- 确认PubSub Topic所在的GCP项目ID和代码中填写的
tokyo-ring-<secret>完全一致,Topic名称webscraping无拼写错误 - 进入Cloud Function的配置页,找到运行时服务账号,给该账号授予对应Topic的
Pub/Sub 发布者权限
内容的提问来源于stack exchange,提问作者mesib
相关产品推荐
相关产品推荐

