简体   繁体   中英

How to select element trough xpath in Selenium and Python?

I want to check the innertext of a web element, but xpath does not find it even if i gave it the absolute path. I get no such element error on the line where i try to define 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)

在此处输入图片说明

  1. Always add some implicit wait after initiating the webdriver.

     driver = webdriver.Firefox() driver.implicitly_wait(10) # seconds 
  2. Try with the below xpath.

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

    or

     "//div[@class='KambiBC-bet-offer-subcategory__container']/h3[1]" 

Hope this helps. Thanks.

EDIT: Its always advisable to use the implicit wait. We can handle the same using the explicit wait also. But we need to add the explicit wait for each and every element. Also there is a good change you might miss adding explicit wait to few elements and debug again. The choice is yours always.

尝试使用.get_attriute("value").get_attribute("innerHTML")而不是.text

Try below :

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

hope it will help you :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM