簡體   English   中英

XPath 使用 Selenium 問題

[英]XPath issue using Selenium

我想刮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()

您在這里使用了錯誤的定位器。

將每個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) # Leave a 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()

下面的 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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM