python - 如何获取在python中不断变化的元素的文本
问题描述
我只是想自动化像Replika(聊天机器人)这样的网站。在其中,一个新的聊天总是不断出现,但带有一个全新的 xpath 和 id。我越来越难以跟踪最近与 selenium 的聊天。我确实尝试了此处和此处列出的解决方案,但它们对我不起作用(或者我做错了什么)。我刚开始使用硒,所以我对它了解不多。请帮帮我。我正在使用 python 3.8.2。
这是代码:
from selenium import webdriver
import time
from selenium.webdriver.common.keys import Keys
from bs4 import BeautifulSoup
from urllib.request import urlopen
browser = webdriver.Chrome("C:\Chromedriver\chromedriver.exe")
browser.get("https://my.replika.ai/")
time.sleep(3)
browser.find_element_by_xpath("""//*
[@id="root"]/div/div[1]/main/a[2]""").click()
time.sleep(2)
### Login ###
browser.find_element_by_xpath("""//*
[@id="emailOrPhone"]""").send_keys("gmail_id")
time.sleep(1)
browser.find_element_by_xpath("""//*[@id="loginForm"]/button""").click()
time.sleep(3)
### Password ###
browser.find_element_by_xpath("""//*[@id="login-
password"]""").send_keys("gmail_password")
time.sleep(1)
browser.find_element_by_xpath("""//*[@id="loginForm"]/button""").click()
time.sleep(10)
### Accept the cookies ###
browser.find_element_by_xpath("""//*
[@id="root"]/div/div[1]/div[1]/button""").click()
time.sleep(5)
### Getting the Latest text ### Here is where it doesn't work
# This is a implementation that I tried and it didn't work
url = "https://my.replika.ai/"
# We use try-except in case the request was unsuccessful because of
# wrong URL
try:
page = urlopen(url)
except Exception:
print("Error opening the URL")
soup = BeautifulSoup(page, 'html.parser')
content = soup.find('div', {"id": "chat-messages"})
chat = ''
for i in content.findAll('span'):
chat = chat + ' ' + i.text
print(chat)
提前致谢。
解决方案
browser = webdriver.Chrome()
browser.get("https://my.replika.ai/")
time.sleep(3)
browser.find_element_by_xpath("""//*
[@id="root"]/div/div[1]/main/a[2]""").click()
time.sleep(2)
### Login ###
browser.find_element_by_xpath("""//*
[@id="emailOrPhone"]""").send_keys("username")
time.sleep(1)
browser.find_element_by_xpath("""//*[@id="loginForm"]/button""").click()
time.sleep(5)
### Password ###
browser.find_element_by_xpath("""//*[@id="login-password"]""").send_keys("password")
time.sleep(1)
browser.find_element_by_xpath("""//*[@id="loginForm"]/button""").click()
time.sleep(3)
### Accept the cookies ###
browser.find_element_by_xpath("""//*
[@id="root"]/div/div[1]/div[1]/button""").click()
time.sleep(5)
a = browser.find_elements(By.XPATH, "//*[@data-author]")
print([i.text for i in a])
print("last text : " + a[-1].text)
只需使用定位器 browser.find_elements(By.XPATH, "//*[@data-author]")
这会找到所有具有 @data-author 属性的元素(只有 chat 具有此属性)并访问 a[-1] 以获取最后一个元素。调用 a[-1].text 从中获取文本
推荐阅读
- javascript - 刷新页面时npm http-server“找不到页面”
- python - 如何获取子文件夹中脚本的路径
- java - 多数据库对象的 Comment-Feature 设计
- sonarqube - 从 SonarQube 中的注释行中删除代码行数
- android - 如何在 RecyclerView 中的 CardViews 之间设置相等的空间?
- c# - Textarea中的最小长度不起作用
- mongodb - MongoDB中的分布式事务
- c# - 如何为可以覆盖值的不同环境创建多个 app.config
- python - 如何在 python3 中的慢速测试中提前失败(例如设置超时)(最好使用鼻子)
- angular - 在量角器中运行每个测试用例后重置数据库状态