Xpath 没有使用 Splinter/Selenium Python 3 选择正确的元素

不确定我是否在这里犯了一个愚蠢的错误,我已经搜索了所有内容,但我无法弄清楚这一点。我真的很感激你的帮助。


我正在尝试制作一个抓取工具来抓取 Google Map Pack 数据。我正在使用 Splinter 来做到这一点。我已经设法选择了每个地图包项目的 div,但我想然后遍历并选择每个 div 的标题(和其他元素)。


但是,当我尝试这样做时,它总是选择第一个元素的标题,即使我在单个元素上运行 find_by_xpath 也是如此。


这是我的代码:


from splinter import Browser

from selenium import webdriver

import time


chrome_options = webdriver.ChromeOptions()

browser = Browser('chrome', options=chrome_options)



browser.visit("https://google.com")


browser.fill('q', 'roofing laredo tx')

# Find and click the 'search' button

time.sleep(5)

button = browser.find_by_name('btnK')

# Interact with elements

button.click()

time.sleep(5)

maps_elements = browser.find_by_xpath("//div[contains(@class,'VkpGBb')]")


for map_element in maps_elements:

    # print(map_element.text)

    title = map_element.find_by_xpath("//div[contains(@class,'dbg0pd')]/span").text

    print(title)

所以我想要的是:JJ Flores Roofing & Construction HBC Roofing McAllen Valley Roofing Co


但我得到了


JJ弗洛雷斯屋面和建筑 JJ弗洛雷斯屋面和建筑 JJ弗洛雷斯屋面和建筑


桃花长相依
浏览 230回答 3
3回答

蛊毒传说

编辑:你得到了重复的结果,因为从循环它选择根元素//它应该是相对的或选择子元素,./但它仍然不起作用,并且可能是分裂错误。但尝试使用 CSS 选择器for map_element in maps_elements:     # select relative but failed    #title = map_element.find_by_xpath("./div[contains(@class,'dbg0pd')]/span")    title = map_element.find_by_css("div[class*='dbg0pd'] > span").text    print(title)变量中的错字,s从title = maps_elements.....#title = map_element.....

慕斯王

这是正确的,因为您不能在 for 循环中声明一个变量,然后在其中创建该变量。您需要在初始化循环之前创建变量才能使其工作。title_elements = browser.find_by_xpath("//div[contains(@class,'dbg0pd')]/span")for title_element in title_elements:    title = title_element.text    print(title)

临摹微笑

更改您的代码:maps_elements = browser.find_by_xpath("//div[contains(@class,'VkpGBb')]")for map_element in maps_elements:    # print(map_element.text)    title = maps_elements.find_by_xpath("//div[contains(@class,'dbg0pd')]/span").text    print(title)到title_elements = browser.find_by_xpath("//div[contains(@class,'dbg0pd')]/span")for title_element in title_elements:    title = title_element.text    print(title)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python