如何在Selenium和Python中选择元素槽xpath?

时间:2017-08-30 10:27:45

标签: python selenium

我想检查一个web元素的innertext,但即使我给它绝对路径,xpath也找不到它。我在尝试定义Plaje

的行上没有出现这样的元素错误
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

driver = webdriver.Edge("D:\pariuri\python\MicrosoftWebDriver.exe")

driver.get("https://www.unibet.ro/betting#filter/all/all/all/all/in-play")

try:
    element_present = EC.presence_of_element_located((By.CLASS_NAME, 'KambiBC-event-result__score-list'))
    WebDriverWait(driver, 4).until(element_present)
except TimeoutException:
    print ('Timed out waiting for page to load') 

event = driver.find_elements_by_class_name('KambiBC-event-item KambiBC-event-item--type-match') 

for items in event:
   link = items.find_element_by_class_name('KambiBC-event-item__link')
   scoruri =  items.find_element_by_class_name('KambiBC-event-item__score-container') 

   scor1 =  scoruri.find_element_by_xpath(".//li[@class='KambiBC-event-result__match']/span[1]")
   scor2 =  scoruri.find_element_by_xpath(".//li[@class='KambiBC-event-result__match']/span[2]")

   print (scor1.text)
   print (scor2.text)
   if scor1.text == '0' and scor2.text == '0':

        link.click()
        Plaje = driver.find_element_by_xpath(".//*[@id='KambiBC-contentWrapper__bottom']/div/div/div/div/div[2]/div[2]/div[3]/div/div/div[4]/div[1]/div[4]/div[2]/div/div/ul/li[2]/ul/li[6]/div[1]/h3")
        print (Plaje.text)

enter image description here

3 个答案:

答案 0 :(得分:1)

  1. 启动webdriver后始终添加一些隐式等待。

    driver = webdriver.Firefox()
    driver.implicitly_wait(10) # seconds
    
  2. 尝试使用以下xpath。

    "//h3[contains(text(),'Total goluri']"
    

    "//div[@class='KambiBC-bet-offer-subcategory__container']/h3[1]"
    
  3. 希望这会有所帮助。感谢。

    编辑:始终建议使用隐式等待。我们也可以使用显式等待来处理相同的事情。但我们需要为每个元素添加显式等待。还有一个很好的改变,你可能会错过添加显式等待几个元素和再次调试。你的选择永远都是你的。

答案 1 :(得分:0)

尝试使用.get_attriute("value").get_attribute("innerHTML")代替.text

答案 2 :(得分:0)

尝试以下:

//h3[contains(.,'Total goluri')]

希望它会对你有所帮助:)。