简体   繁体   English

什么是 Python 的 .text 的 JavaScript 等价物?

[英]What is the JavaScript equivalent of python's .text?

Element.text returns the text content of an element. Element.text 返回元素的文本内容。

In a different thread on SO, the python script scrapes data from the followers modal on an Instagram account.在 SO 上的另一个线程中,python 脚本从 Instagram 帐户上的关注者模式中抓取数据。 The following part returns the text inside the lists and stores them in an array.以下部分返回列表中的文本并将它们存储在数组中。

 xpath = "//div[@style='position: relative; z-index: 1;']//ul/li/div/div/div/div/a"
 followers_elems = driver.find_elements_by_xpath(xpath)
 return [e.text for e in followers_elems]

I'm trying to achieve a similar result in JavaScript (I'm using WebDriverJS) :我正在尝试在 JavaScript 中实现类似的结果(我使用的是 WebDriverJS):

 const XPATH = "/html/body/div[3]/div/div[2]/div/div[2]/ul/div/li";
 var followers_elems = await driver.findElements(By.xpath(XPATH));
 var followers_temp = [];
 for (var e in followers_elems) {
  followers_temp.push(e.textContent); }
 console.log(followers_temp);

I'm not sure if textContent is the right property for .text .我不确定 textContent 是否是 .text 的正确属性。

I've tried a million different alternatives but all I'm getting is undefined values in the array :我已经尝试了一百万种不同的替代方案,但我得到的只是数组中未定义的值:

在此处输入图片说明

I'm not very proficient with JS yet, but I'm sure e is reading from followers_elems and if I push just e inside the array it can log the total follower numbers just fine.我还不是很精通 JS,但我确定e正在从followers_elems读取,如果我只将e推入数组,它可以很好地记录总关注者人数。 It is getting the text value from xpath that I'm not understanding.它从我不理解的 xpath 获取文本值。 Python does this so elegantly but despite the verbose JavaScript is failing me. Python 做到了如此优雅,但尽管冗长的 JavaScript 令我失望。

Thank you.谢谢你。

WebElement.getText() is the javascript equivalent of getting text element in python when using WebdriverJS. WebElement.getText() 是使用 WebdriverJS 时在 python 中获取文本元素的 javascript 等效项。

This should work for you.这应该对你有用。 I have created an async function and easy to understand for loop.我创建了一个异步函数并且易于理解 for 循环。 Also, since getText() return a promise so i am using async - await to get the text and push it to the followers_temp array.此外,由于 getText() 返回一个承诺,所以我使用 async - await 获取文本并将其推送到 follower_temp 数组。

async function pushTextIn() {
  for (let i = 0; i < followers_elems.length; i++) {
    let text = await followers_elems[i].getText();
    console.log('pushing text: ', text);
    followers_temp.push(text);
  }
  return followers_temp;
}

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

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