为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

桃花长相依 2021-09-01 14:46:17
不确定我是否在这里犯了一个愚蠢的错误,我已经搜索了所有内容,但我无法弄清楚这一点。我真的很感激你的帮助。我正在尝试制作一个抓取工具来抓取 Google Map Pack 数据。我正在使用 Splinter 来做到这一点。我已经设法选择了每个地图包项目的 div,但我想然后遍历并选择每个 div 的标题(和其他元素)。但是,当我尝试这样做时,它总是选择第一个元素的标题,即使我在单个元素上运行 find_by_xpath 也是如此。这是我的代码:from splinter import Browserfrom selenium import webdriverimport timechrome_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' buttontime.sleep(5)button = browser.find_by_name('btnK')# Interact with elementsbutton.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弗洛雷斯屋面和建筑
查看完整描述

3 回答

?
蛊毒传说

TA贡献1895条经验 获得超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.....


查看完整回答
反对 回复 2021-09-01
?
慕斯王

TA贡献1864条经验 获得超2个赞

这是正确的,因为您不能在 for 循环中声明一个变量,然后在其中创建该变量。您需要在初始化循环之前创建变量才能使其工作。


title_elements = browser.find_by_xpath("//div[contains(@class,'dbg0pd')]/span")


for title_element in title_elements:

    title = title_element.text

    print(title)


查看完整回答
反对 回复 2021-09-01
?
临摹微笑

TA贡献1982条经验 获得超2个赞

更改您的代码:


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)


查看完整回答
反对 回复 2021-09-01
  • 3 回答
  • 0 关注
  • 229 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号