pycharm 标题:GoogleMap中有5个结果

gfttwv5a  于 2023-10-20  发布在  PyCharm
关注(0)|答案(2)|浏览(143)

我试着从谷歌Map上打印出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()

我在寻求帮助

vngu2lb8

vngu2lb81#

下面是一个完整的脚本(基于您的设置),它直接指向搜索结果的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()
ma8fv8wu

ma8fv8wu2#

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

//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

相关问题