Google 地图中 5 个结果的标题

问题描述 投票:0回答:2

我正在尝试从谷歌地图打印 5 所第一所工程学校的名称。我做了下面的代码但是我不知道为什么运行后没有结果!

你能帮忙吗?

提前非常感谢。

from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
import time

chrome_options = Options()
chrome_options.add_experimental_option("detach", True)

driver = webdriver.Chrome(options=chrome_options)

driver.get("https://www.google.com/")
driver.find_element(By.ID, "L2AGLb").click()

driver.get("https://www.google.com/maps")

# Wait for the page to load and display the search box
time.sleep(3)

# Input the search query for "parisserie in Paris" and press Enter
search_box = driver.find_element(By.ID, "searchboxinput")
search_box.send_keys("engineering school in london")
search_box.send_keys(Keys.RETURN)

# Wait for the search results to load
time.sleep(5)

# Get the names of the first 5 results using "aria-label"
results = driver.find_elements(By.XPATH, "//a[@class='place-result-container-place-link']/@aria-label")

# Print the names for debugging
for i, result in enumerate(results[:5], start=1):
    print(f"Result {i}: {result}")

# Close the browser
driver.quit()

我正在寻求帮助

selenium-webdriver pycharm
2个回答
0
投票

问题:您下面的 XPath 表达式似乎不正确,我没有看到它定位任何元素。

//a[@class='place-result-container-place-link']/@aria-label

检查以下工作代码:

search_box = driver.find_element(By.ID, "searchboxinput")
search_box.send_keys("engineering school in london")
search_box.send_keys(Keys.RETURN)

# Wait for the search results to load
time.sleep(5)

# Get the elements based on the below XPath locator
results = driver.find_elements(By.XPATH, "//a[@class='hfpxzc']")

# Print the names for debugging
for i, result in enumerate(results[:5], start=1):
    print(f"Result {i}: {result.get_attribute('aria-label')}")

# Close the browser
driver.quit()

控制台输出:

Result 1: London Design and Engineering UTC
Result 2: UCL Faculty of Engineering Sciences
Result 3: School of Computing and Engineering
Result 4: Dyson School of Design Engineering, Imperial College London
Result 5: QMUL School of Engineering and Materials Science

Process finished with exit code 0

0
投票

这是一个完整的脚本(基于您的设置),它直接转到包含搜索结果的 URL,并使用更好的选择器来查找学校名称:

from selenium import webdriver
from selenium.webdriver.chrome.options import Options
import time

chrome_options = Options()
chrome_options.add_experimental_option("detach", True)
driver = webdriver.Chrome(options=chrome_options)
driver.get("https://www.google.com/maps/search/engineering+school+in+london")
time.sleep(5)
elements = driver.find_elements('css selector', '[role="main"] a[href*="google"]')
results = [element.get_attribute("aria-label") for element in elements]
for i, result in enumerate(results[:5], start=1):
    print(f"Result {i}: {result}")
driver.quit()
© www.soinside.com 2019 - 2024. All rights reserved.