[英]find_elements_by_xpath sometimes return an emply list?
So I'm working on a program that will scrape information from Grailed ( https://www.grailed.com/ ), and my problem is that sometimes my call to selenium will return the data I want, but sometimes it returns an empty list.所以我正在开发一个程序,该程序将从 Grailed ( https://www.grailed.com/ ) 中抓取信息,我的问题是有时我对 selenium 的调用会返回我想要的数据,但有时它会返回一个空的数据列表。 I'm new to Selenium and just trying to get a hang on how it works, I can't find a pattern to when it returns an empty list so I'm kind of stumped.
我是 Selenium 的新手,只是想了解它的工作原理,当它返回一个空列表时我找不到模式,所以我有点难过。
from selenium import webdriver
driver = webdriver.Chrome("Path to Chromedriver")
driver.get('https://www.grailed.com/designers/jordan-brand/hi-top-sneakers')
item = driver.find_elements_by_xpath('//html/body/div[3]/div[6]/div[3]/div[3]/div[2]/div[2]/div[1]/a/div[3]/div[1]/p[1]')
print(item)
One thing I would think is that the item specified by the xpath changes when you load the page again, but the xpath stays the same so I don't think that's it.我想的一件事是,当您再次加载页面时,xpath 指定的项目会发生变化,但 xpath 保持不变,所以我不认为就是这样。 Does anyone know why this is inconsistent in it's return, and how I can fix it?
有谁知道为什么它的回报不一致,我该如何解决?
Induce WebDriverWait
() and wait for visibility_of_all_elements_located
() and below xpath.诱导
WebDriverWait
()并等待visibility_of_all_elements_located
()及xpath以下。
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
driver=webdriver.Chrome("Path to Chromedriver")
driver.get("https://www.grailed.com/designers/jordan-brand/hi-top-sneakers")
elements=WebDriverWait(driver,10).until(EC.visibility_of_all_elements_located((By.XPATH,"//div[@class='feed-item']//div[@class='listing-designer-and-size']/p[@class='listing-designer truncate']")))
itemlist=[item.text for item in elements ]
print(itemlist)
Output : Output :
['JORDAN BRAND', 'JORDAN BRAND', 'JORDAN BRAND', 'JORDAN BRAND', 'JORDAN BRAND', 'JORDAN BRAND × NIKE', 'JORDAN BRAND', 'JORDAN BRAND', 'JORDAN BRAND', 'JORDAN BRAND × NIKE', 'JORDAN BRAND', 'JORDAN BRAND × NIKE', 'JORDAN BRAND', 'JORDAN BRAND', 'JORDAN BRAND', 'JORDAN BRAND × NIKE', 'JORDAN BRAND × NIKE', 'JORDAN BRAND', 'JORDAN BRAND × NIKE', 'JORDAN BRAND × NIKE', 'JORDAN BRAND', 'JORDAN BRAND × NIKE', 'JORDAN BRAND', 'JORDAN BRAND', 'JORDAN BRAND', 'JORDAN BRAND', 'JORDAN BRAND', 'JORDAN BRAND', 'JORDAN BRAND × NIKE', 'JORDAN BRAND', 'JORDAN BRAND', 'JORDAN BRAND', 'JORDAN BRAND', 'JORDAN BRAND × NIKE', 'JORDAN BRAND × NIKE', 'JORDAN BRAND', 'JORDAN BRAND', 'JORDAN BRAND × NIKE × VINTAGE', 'JORDAN BRAND', 'JORDAN BRAND']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.