【问题标题】:Get text from span (Whatsapp Web)从跨度获取文本(Whatsapp Web)
【发布时间】:2021-01-07 04:42:28
【问题描述】:

我正在使用 Selenium 学习 Python,我想从 whatsapp 群组对话中的最后一条消息中获取用户名。我尝试了多种方法,但都做不到。

例如: 我想从这部分获取文本“Nay”并将其存储在变量中。

<span dir="auto" class="FMlAw FdF4z _3Whw5">Nay</span>

Print Screen

我试过了:

 texto1 = post[ultimo].find_element_by_xpath("//span[@class_name = 'FMlAw FdF4z _3Whw5']").text

但我得到一个错误 AttributeError: 'NoneType' object has no attribute 'text'

我用下面的代码取得了相对成功,但是除了复制用户名之外,这还复制了消息

texto1 = post[ultimo].find_element_by_class_name("_3Whw5").text

抱歉,我正在使用谷歌翻译。

谢谢。

【问题讨论】:

  • 最后一个函数的输出是什么样的?是否以可预测的格式出现,以便您可以从字符串中删除用户名?例如。 texto1 = ['username','message1','message'] 导致解决方案texto1 = " ".join(texto1[1:])
  • 尝试使用.innerText,如果不起作用,则使用.outerText 并解析您的字符串。
  • //span[@class_name 应该是 //span[@class

标签: python html css selenium selenium-webdriver


【解决方案1】:
#get all messsages as a list
messages = driver.find_elements_by_xpath("//div[contains(@class,'message-in focusable-list-item')]/following::span[contains(@class,'selectable-text')]/span")

#reverse the list so you can get easier the last element 
messages.reverse()

#last element becomes the first - now you can use it, I printed for the purpose of testing
print(messages[0].text)

【讨论】:

  • 谢谢!!!!!!
  • 你能把答案标记为正确吗?
猜你喜欢
  • 2021-04-25
  • 2017-09-27
  • 1970-01-01
  • 2016-12-18
  • 2019-01-29
  • 1970-01-01
  • 1970-01-01
  • 2011-08-16
相关资源
最近更新 更多