你好,Stackoverflow社区,
我目前正在开发一个Python脚本,使用Selenium在无头Chrome中通过WhatsApp Web自动发送图像。但是,我在使用xpath定位元素时遇到了一个错误。以下是我收到的错误消息:
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/selenium/webdriver/remote/errorhandler.py", line 245, in check_response
raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"//div/span[@title='Bookmark']"}
(Session info: headless chrome=113.0.5672.92)
我正试图在WhatsApp Web中通过使用xpath//div/span[@title=“书签”]定位元素来选择聊天。当我在非无头模式下运行脚本时,它运行得很好,但当我切换到无头模式时,Selenium似乎无法定位元素。
在尝试定位元素之前,我已经尝试添加显式等待和延迟,但仍然遇到同样的错误。我还通过手动检查页面来确认我使用的xpath是正确的。
以下是相关的代码片段:
chat_name = "Bookmark"
search_box = driver.find_element(By.XPATH, "//div/span[@title='Bookmark']")
我使用的是无头Chrome版本113.0.5672.92和Selenium的最新版本。关于如何解决此问题的任何帮助或建议
import requests
import time
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.chrome.options import Options
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.chrome.service import Service
# Set up Chrome options to run in headless mode
options = webdriver.ChromeOptions()
options.add_argument('--headless')
options.add_argument('--disable-gpu')
# Launch Chrome browser and navigate to WhatsApp Web
driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()), options=options)
driver.get("https://web.whatsapp.com/")
# Select the chat or group
chat_name = "Bookmark"
search_box = driver.find_element(By.XPATH, "//div/span[@title='Bookmark']")
search_box.send_keys(chat_name)
search_box.send_keys(Keys.RETURN)
time.sleep(5) # Make sure chat opens
# Attach and send the image
attachment_box = driver.find_element_by_xpath("//div[contains(@title, 'Attach')]")
attachment_box.click()
time.sleep(2) # wait for the file dialog to open
upload_button = driver.find_element_by_xpath("//input[@type='file']")
upload_button.send_keys("/Users/rajeevranjanpandey/Desktop/Screenshot 2023-04-11 at 3.44.43 PM.png")
time.sleep(10) # wait for the image to upload
# Send the image
send_button = driver.find_element_by_xpath("//span[@data-icon='send']")
send_button.click()
# Close the browser
driver.quit()
我尝试过:
重新检查页面后更新XPath选择器
使用CSS选择器而不是XPath
在没有--headless参数的情况下运行
导航到页面后添加time.sleep(10)
但我仍然无法找到元素。WhatsApp网络似乎已经做出了重大改变,我的传统方法也不起作用。
如何修复此问题并使脚本重新工作?非常感谢您的帮助!如果你需要我提供更多信息,请告诉我。