如何自动化处理邮政编码,获取Sklavenitis超市网页商品数量?
可行方案建议
方案一:直接在Scrapy中设置有效HubID Cookie(最优)
手动通过开发者工具获取一个有效的HubID(比如选好目标区域后,复制Cookie里的HubID值),直接在Scrapy请求中携带该Cookie,无需模拟前端交互,效率最高。
示例代码:
def start_requests(self): target_url = "https://www.sklavenitis.gr/eidi-artozacharoplasteioy/keik-tsoyrekia-kroyasan/" # 替换为你手动获取的有效HubID,可补充其他必要Cookie(如session类) cookies = {'HubID': 'your_valid_hub_id'} yield scrapy.Request(target_url, cookies=cookies, callback=self.parse)
方案二:修复Selenium动态下拉选择问题
如果必须模拟用户选择区域的流程,需确保等待元素加载完成后再操作,避免因动态渲染导致定位失败。
示例代码:
from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC driver = webdriver.Chrome() driver.get("https://www.sklavenitis.gr") # 等待邮编输入框加载并输入目标邮编 zip_input = WebDriverWait(driver, 10).until( EC.presence_of_element_located((By.CSS_SELECTOR, "input[name='zipCode']")) # 替换为实际选择器 ) zip_input.send_keys("10100") # 替换为目标邮编 # 等待下拉选项加载并点击目标区域 target_option = WebDriverWait(driver, 10).until( EC.element_to_be_clickable((By.XPATH, "//li[contains(text(), '目标区域名称')]")) # 替换为实际选项定位 ) target_option.click() # 获取HubID后可传入Scrapy使用,或直接用Selenium访问分类页统计数量 hub_id = driver.get_cookie("HubID")['value']
注意:需根据实际网页的元素结构调整选择器,部分下拉选项是AJAX异步加载,需等待接口请求完成后再定位。
方案三:调用区域API获取HubID
观察官网选择邮编时的网络请求,找到返回HubID的API接口,直接通过Scrapy请求该接口获取目标HubID,再携带Cookie访问分类页。
示例代码:
import scrapy import json class SklavenitisSpider(scrapy.Spider): name = 'sklavenitis' zip_api_url = "https://www.sklavenitis.gr/api/v1/location/hub" # 替换为实际API地址 def start_requests(self): # 发送邮编请求获取HubID yield scrapy.FormRequest( url=self.zip_api_url, formdata={'zipCode': '10100'}, # 替换为目标邮编 callback=self.parse_hub_id ) def parse_hub_id(self, response): res_data = json.loads(response.text) hub_id = res_data.get('hubId') # 根据实际返回结构调整字段名 if hub_id: category_url = "https://www.sklavenitis.gr/eidi-artozacharoplasteioy/keik-tsoyrekia-kroyasan/" yield scrapy.Request( category_url, cookies={'HubID': hub_id}, callback=self.parse_product_count ) def parse_product_count(self, response): # 提取商品数量,替换为实际页面选择器 product_count = response.css(".product-count::text").get() self.logger.info(f"商品数量:{product_count}")
方案优先级推荐
- 优先选方案一:操作简单,效率最高,适合HubID长期有效的场景;
- 若HubID易过期,选方案三:完全模拟前端逻辑,无需依赖Selenium,稳定性强;
- 方案二作为兜底:仅在API接口难以定位时使用,需处理更多前端渲染细节。
内容的提问来源于stack exchange,提问作者Starski
相关产品推荐
相关产品推荐

