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

如何从指定网站提取餐厅URL?Selenium返回None的问题排查

解决Selenium获取餐厅URL返回None的问题

问题原因

你使用div.restaurant-info作为选择器,但这个div元素本身没有href属性——餐厅的URL实际存储在该div内部嵌套的<a>标签上,所以直接获取div的href会返回None。

修正后的代码

from selenium import webdriver
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager

# 初始化浏览器
driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()))
driver.get('https://btownmenus.com/some/bloomington/delivery/all')

# 等待页面动态加载完成
wait = WebDriverWait(driver, 10)
# 直接定位到包含URL的a标签(父容器为div.restaurant-info)
restaurant_links = wait.until(EC.presence_of_all_elements_located(
    (By.CSS_SELECTOR, "div.restaurant-info > a")
))

# 提取每个a标签的href属性
urls = [link.get_attribute('href') for link in restaurant_links]
print(urls)

# 关闭浏览器
driver.quit()

关键改动说明

  • 修正选择器:用div.restaurant-info > a直接定位到带href的a标签,这才是存储餐厅URL的目标元素。
  • 添加显式等待:页面为动态渲染,通过WebDriverWait确保元素完全加载后再获取,避免因元素未渲染导致空列表。
  • 正确提取属性:从a标签而非父div中获取href值。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 11:36:14