Home > Net >  locating element via selenium xpath
locating element via selenium xpath

Time:10-30

I am trying to locate below element from enter link description here with this code x_title=driver.find_element(By.XPATH,'//h2/a/span[@]')

it gives an error of selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"//h2/a/span[@]"}

<div >
   <h2 >
      <a  href="/Love-Languages-Secret-that-Lasts/dp/080241270X/ref=sr_1_1?qid=1667035762&amp;refinements=p_n_feature_eighteen_browse-bin:8622846011&amp;rnid=8622845011&amp;s=books&amp;sr=1-1">
         <span >The 5 Love Languages: The Secret to Love that Lasts</span>
     </a> 
   </h2>
<div ><div ><a  href="/dp/B07VVJPJ5Z?binding=kindle_edition&amp;searchxofy=true&amp;qid=1667035762&amp;sr=1-1"><span>Part of: The 5 Love Languages Series (11 books)</span> </a> <span ></span><span > | </span><span ></span><span >by </span><a  href="/Gary-Chapman/e/B01IAEQ73Q?ref=sr_ntt_srch_lnk_1&amp;qid=1667035762&amp;sr=1-1">Gary Chapman</a> <span ></span><span > | </span><span ></span><span >Jan 1, 2015</span></div></div></div>

Here is xpath of element; //*[@id="search"]/div[1]/div[1]/div/span[1]/div[1]/div[2]/div/div/div/div/div/div[2]/div/div/div[1]/h2/a/span

Edit: I have also tried x_title=driver.find_element(By.XPATH,'//div[@]//span[@]')

error trace: selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"//div[@]//span[@]"}

CodePudding user response:

Your mistake is that elements have multiple class names. Not only a-size-medium and s-title-instructions-style.
So, instead //div[@]//span[@] it should be

"//div[contains(@class,"s-title-instructions-style")]//span[contains(@class,"a-size-medium")]"

You can also use this CSS Selector, it looks shorter

".s-title-instructions-style .a-size-medium"
  • Related