1

how to get multiple link under-class tag,HTML contain multiple multiple class tag="blog-item-wrap" each tag contain tag . need to get all the href links under-clas's tag

<div class="blog-item-wrap">
            <a href="https://website.com/data-wrangling-with/" title="Data 
Wrangling with JavaScript">
                        </a>
   </div>
  <div .... >
  <div class="blog-item-wrap">
            <a href="https://website.com/data-wrangling-with/" title="Data 
    Wrangling with JavaScript">
                        </a>
    </div>
     </div>

using this and getting error:

StaleElementReferenceError: stale element reference: element is not attached to the page document

browser.findElement(By.xpath('//*[@class="blog-item-wrap"]/a')).then(res => {  res.getText().then(text => { console.log('text', text); }).catch(err => { console.log('err', err); });
Moshe Slavin
  • 5,127
  • 5
  • 23
  • 38
Atiq Ur Rehman
  • 230
  • 2
  • 13
  • How did you try? Share your code and exception log – Andersson Dec 16 '18 at 15:59
  • Based on this answer: https://stackoverflow.com/questions/5543724/selenium-how-to-select-an-object-by-class you should use XPATH `//div[contains(@class, 'ui-autocomplete')]/a` – ymz Dec 16 '18 at 16:04
  • browser.findElement(By.xpath('//*[@class="blog-item-wrap"]/a')).then(res => { console.log(res); res.getText().then(text => { console.log('text', text); }).catch(err => { console.log('err', err); }); – Atiq Ur Rehman Dec 16 '18 at 16:18
  • trying this but getting error UnhandledPromiseRejectionWarning: StaleElementReferenceError: stale element reference: element is not attached to the page documen – Atiq Ur Rehman Dec 16 '18 at 16:18

2 Answers2

2

You should use getAttribute("href") on all the elements with driver.findElements(By.xpath('//*[@class="blog-item-wrap"]/a')).

Then iterate the list with the getAttribute("href").

you should think about using async...

Hope this helps you!

Moshe Slavin
  • 5,127
  • 5
  • 23
  • 38
1

The error come because the element removed or modified from the page try using Promise and use findElements() to get all elements.

browser.get('https://..........')
.then(() => {
  browser.findElements(By.xpath('//*[@class="blog-item-wrap"]//a'))
  .then(res => {
    var links = res.map(aTags => aTags.getText()) // .getAttribute("href")
    Promise.all(links).then(texts => {
      texts.forEach(text => console.log('text: ', text))
    })
  })
  .catch(err => {
    console.log('err: ', err);
  });
})

Non Promise

browser.get('https://....')
  .then(() => {
    browser.findElements(By.xpath('//*[@class="blog-item-wrap"]//a'))
    .then(res => {
      res.forEach(aTags => {
        aTags.getText()
        //aTags.getAttribute("href")
        .then(text => console.log('text: ', text))
        .catch(err => console.log('err: ', err))
    })
  })
})
ewwink
  • 18,382
  • 2
  • 44
  • 54