不确定我是否在这里犯了一个愚蠢的错误,我已经搜索了所有内容,但无法弄清楚这个错误。非常感谢您的帮助。
我正试图制作一个刮板来刮除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)
所以我想要的是: J J Flores屋顶与建筑 HBC屋面 麦卡伦山谷屋面公司
但是我得到了
J J Flores屋顶与建筑 J J Flores屋顶与建筑 J J Flores屋顶与建筑
答案 0 :(得分:1)
更改代码:
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)
答案 1 :(得分:0)
编辑:
您得到了重复的结果,因为从循环中选择根元素//
应该是相对的,或者选择./
来选择子元素,但仍然无效,并且可能会产生错误。但是尝试使用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)
typo变量中,从
中删除s
title = maps_elements.....
#title = map_element.....
答案 2 :(得分:0)
这是正确的,因为您不能在for循环中声明变量,然后在其中创建该变量。您需要在初始化循环之前创建变量,以使其起作用。
title_elements = browser.find_by_xpath("//div[contains(@class,'dbg0pd')]/span")
for title_element in title_elements:
title = title_element.text
print(title)