我正在嘗試抓取title,但他們說您的 xpath 錯誤
from selenium.webdriver.common.by import By
from selenium import webdriver
from time import sleep
PATH="C:\Program Files (x86)\chromedriver.exe"
url='https://www.nationalhardwareshow.com/en-us/attend/exhibitor-list.html'
driver =webdriver.Chrome(PATH)
driver.get(url)
sleep(2)
def searchplace():
vid = driver.find_elements(By.XPATH, "//div[@class='row']")
for item in vid:
title=item.find_element_by_xpath(".//div[@class='company-info']//h3").text
print(title)
searchplace()
uj5u.com熱心網友回復:
您在這里使用了錯誤的定位器。
每個vid帶有此 XPath 的塊://div[contains(@class,'directory-item directory-item-feature-toggled')].
這樣,您的代碼將如下所示:
from selenium.webdriver.common.by import By
from selenium import webdriver
from time import sleep
PATH="C:\Program Files (x86)\chromedriver.exe"
url='https://www.nationalhardwareshow.com/en-us/attend/exhibitor-list.html'
driver =webdriver.Chrome(PATH)
driver.get(url)
sleep(2)
def searchplace():
vid = driver.find_elements(By.XPATH, "//div[contains(@class,'directory-item directory-item-feature-toggled')]")
for item in vid:
title=item.find_element_by_xpath(".//div[@class='company-info']//h3").text
print(title)
searchplace()
我建議您使用預期條件顯式等待而不是硬編碼暫停。
有了它,您的代碼將是:
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium import webdriver
from time import sleep
PATH="C:\Program Files (x86)\chromedriver.exe"
url='https://www.nationalhardwareshow.com/en-us/attend/exhibitor-list.html'
driver =webdriver.Chrome(PATH)
wait = WebDriverWait(driver, 20)
driver.get(url)
wait.until(EC.visibility_of_element_located((By.XPATH, "//div[contains(@class,'directory-item directory-item-feature-toggled')]")))
sleep(0.3) #leaved short delay to make sure not only the first item got visible
def searchplace():
vid = driver.find_elements(By.XPATH, "//div[contains(@class,'directory-item directory-item-feature-toggled')]")
for item in vid:
title=item.find_element_by_xpath(".//div[@class='company-info']//h3").text
print(title)
searchplace()
uj5u.com熱心網友回復:
下面的 xpath 對我有用,試一試。如果需要,還可以嘗試有效地減少 xpath 長度。
vid = driver.find_elements(By.XPATH, "//div[@class='directory-item directory-item-feature-toggled exhibitor-category']")
for item in vid:
title=item.find_element(By.XPATH, "div[@class='row']/div[2]/div//div[@class='company-info']/div/a/h3")
print(title.text)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/439588.html
