抓取Expedia酒店搜索结果时Locator.evaluate_all语法错误求助
问题解决:Playwright抓取Expedia酒店时的语法错误与字段修正
1. 错误根源
你遇到的missing } after property list是JavaScript语法错误:在evaluate_all的回调代码中,返回的对象最后一个属性total_price后面多了一个逗号,不符合严格的JS对象语法规范。
2. 修正后的代码
以下是修复语法错误,并优化选择器(确保精准定位目标字段)的完整代码:
import json from playwright.sync_api import sync_playwright with sync_playwright() as pw: browser = pw.firefox.launch(headless=False) page = browser.new_page() page.goto("https://www.expedia.com/Hotel-Search?adults=2&allowPreAppliedFilters=false&children=&d1=2024-06-21&d2=2024-06-23&destination=Venice%20%28and%20vicinity%29%2C%20Veneto%2C%20Italy&flexibility=6_DAY_LOWER&flexibility=7_DAY_UPPER&flexibleSearchRequirement=INCLUDE_WEEKEND&latLong=45.434031%2C12.338332&mapBounds=®ionId=179981&rooms=1&searchRange=2024-07-01_2024-07-31&semdtl=&sort=RECOMMENDED&stay_options_group=hotels_option&theme=&useRewards=false&userIntent=") # 处理"Show More"按钮,改用等待机制替代固定sleep while True: show_more = page.locator("button", has_text="Show More") if not show_more.is_visible(): break try: show_more.click(timeout=3000) page.wait_for_timeout(2000) # 等待加载,比time.sleep更贴合Playwright机制 except: break # 修复语法错误,并优化选择器确保精准获取字段 hotels = page.locator('[data-stid="lodging-card-responsive"]').evaluate_all(""" els => els.map(el => { const text = s => el.querySelector(s)?.textContent.trim() || null; return { hotel_name: text('h3[data-stid="lodging-card-name"]'), location: text('div[data-stid="content-hotel-neighborhood"]'), rating: text('span.uitk-badge-base-text'), price: text('div[data-stid="price-lockup"] span.uitk-type-500'), total_price: text('div[data-stid="total-price"] span.uitk-type-200') }; }) """) print(json.dumps(hotels, indent=2, ensure_ascii=False)) browser.close()
3. 关键调整说明
- 语法修复:移除了
total_price属性后的多余逗号,符合JS对象字面量语法要求。 - 选择器优化:
- 酒店名称用
h3[data-stid="lodging-card-name"]替代泛用的h3.uitk-heading,避免匹配到其他标题元素。 - 位置用
div[data-stid="content-hotel-neighborhood"]精准定位酒店区域信息。 - 价格和总价分别用带
data-stid的父容器限定范围,防止抓取到页面其他位置的同类型文本。
- 酒店名称用
- 等待机制优化:用
page.wait_for_timeout替代time.sleep,更适配Playwright的异步执行逻辑;点击按钮时增加超时时间,避免无响应时卡死。
内容的提问来源于stack exchange,提问作者Anna Quoc Nguyen
相关产品推荐
相关产品推荐

