简体   繁体   English

webdriver node js在类标记下获取多链接

[英]webdriver node js get multile link under class tag

how to get multiple link under-class tag,HTML contain multiple multiple class tag="blog-item-wrap" each tag contain tag . 如何获取多个链接的下层标签,HTML包含多个多个类tag =“ blog-item-wrap”每个标签都包含tag。 need to get all the href links under-clas's tag 需要获得所有href链接的标签

<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 StaleElementReferenceError:过时的元素引用:元素未附加到页面文档

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); });

You should use getAttribute("href") on all the elements with driver.findElements(By.xpath('//*[@class="blog-item-wrap"]/a')) . 您应该在具有driver.findElements(By.xpath('//*[@class="blog-item-wrap"]/a'))所有元素上使用getAttribute("href") driver.findElements(By.xpath('//*[@class="blog-item-wrap"]/a'))

Then iterate the list with the getAttribute("href") . 然后使用getAttribute("href")迭代列表。

you should think about using async ... 你应该考虑使用async ...

Hope this helps you! 希望这对您有所帮助!

The error come because the element removed or modified from the page try using Promise and use findElements() to get all elements. 出现错误是因为从页面中删除或修改的元素尝试使用Promise并使用findElements()获取所有元素。

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 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))
    })
  })
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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