代码Python/Selenium发送批量WhatsApp消息 - 不断无法找到文本框的元素

发布于 2025-01-27 14:04:38 字数 3313 浏览 4 评论 0原文

查看了许多选项和其他代码。下面代码中的所有内容都顺利运行,直到调用WhatsApp输入框:

*input_box = driver.find_element_by_xpath('//*[@id="main"]/footer/div[1]/div[2]/div/div[2]')*

我还将其调整为:

*input_box = driver.find_element(By.XPATH, '//*@id="main"]/footer/div[1]/div[2]/div/div[2]')*

没有任何成功。我会收到以下错误:


Klaas Malan *(my contact)*
As jy hierdie teks kry, dan werk die program wat ek vir Heiko skrywe. *(Message in Afrikaans)*
https://web.whatsapp.com/send?phone=Klaas Malan&text=As+jy+hierdie+teks+kry%2C+dan+werk+die+program+wat+ek+vir+Heiko+skrywe.&source=&data=
Sending message to Klaas Malan
**Message: no such element: Unable to locate element: {"method":"xpath","selector":"//*[@id="main"]/footer/div[1]/div[2]/div/div[2]"}**
  (Session info: chrome=101.0.4951.54)
Failed to send message

在我的完整代码下方:

from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.common.action_chains import ActionChains

import datetime
import time
import openpyxl as excel
import urllib.parse

# function to read contacts from a text file
def readContacts(fileName):
    lst = []
    file = excel.load_workbook(fileName)
    sheet = file.active
    firstCol = sheet['A']
    secondCol = sheet['B']
    driver  = webdriver.Chrome()
    driver.get('https://web.whatsapp.com')
    time.sleep(60)

    for cell in range(len(firstCol)):
        contact = str(firstCol[cell].value)
        message = str(secondCol[cell].value)
        print(contact)
        print(message)
        link = "https://web.whatsapp.com/send phone="+contact+"&text="+urllib.parse.quote_plus(message)+"&source=&data="
        print(link)  
        driver.get(link)
        time.sleep(4)
        print("Sending message to", contact)

        try:
            time.sleep(7)
            input_box = driver.find_element_by_xpath('//*[@id="main"]/footer/div[1]/div[2]/div/div[2]')
            for ch in message:
                if ch == "\n":
                    ActionChains(driver).key_down(Keys.SHIFT).key_down(Keys.ENTER).key_up(Keys.ENTER).key_up(Keys.SHIFT).key_up(Keys.BACKSPACE).perform()
                else:
                    input_box.send_keys(ch)
            input_box.send_keys(Keys.ENTER)
            print("Message sent successfuly")
        except NoSuchElementException as exc:
            print(exc) # and/or other actions to recover
            print("Failed to send message")

targets = readContacts("./contacts-message.xlsx")

有没有建议或愿意共享其代码的人? 最好的祝愿,伙计们。我是Python和纳米比亚的一个农民的新手,我的目标是向我的每位牛买家致敬。 Emil Jung

这是我可以从消息框的HTML方面找到的:

<div title="Type a message" role="textbox" class="_13NKt copyable-text selectable-text" contenteditable="true" data-tab="10" dir="ltr" spellcheck="true"></div>

WhatsApp的屏幕截图

,WhatsApp的屏幕截图 - 寻找元素。

Looked at many options and other codes. Everything in the code below runs smoothly, until the whatsapp input box is called up with:

*input_box = driver.find_element_by_xpath('//*[@id="main"]/footer/div[1]/div[2]/div/div[2]')*

I have also adjusted it to:

*input_box = driver.find_element(By.XPATH, '//*@id="main"]/footer/div[1]/div[2]/div/div[2]')*

without any success. I get the following error:


Klaas Malan *(my contact)*
As jy hierdie teks kry, dan werk die program wat ek vir Heiko skrywe. *(Message in Afrikaans)*
https://web.whatsapp.com/send?phone=Klaas Malan&text=As+jy+hierdie+teks+kry%2C+dan+werk+die+program+wat+ek+vir+Heiko+skrywe.&source=&data=
Sending message to Klaas Malan
**Message: no such element: Unable to locate element: {"method":"xpath","selector":"//*[@id="main"]/footer/div[1]/div[2]/div/div[2]"}**
  (Session info: chrome=101.0.4951.54)
Failed to send message

Below my full code:

from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.common.action_chains import ActionChains

import datetime
import time
import openpyxl as excel
import urllib.parse

# function to read contacts from a text file
def readContacts(fileName):
    lst = []
    file = excel.load_workbook(fileName)
    sheet = file.active
    firstCol = sheet['A']
    secondCol = sheet['B']
    driver  = webdriver.Chrome()
    driver.get('https://web.whatsapp.com')
    time.sleep(60)

    for cell in range(len(firstCol)):
        contact = str(firstCol[cell].value)
        message = str(secondCol[cell].value)
        print(contact)
        print(message)
        link = "https://web.whatsapp.com/send phone="+contact+"&text="+urllib.parse.quote_plus(message)+"&source=&data="
        print(link)  
        driver.get(link)
        time.sleep(4)
        print("Sending message to", contact)

        try:
            time.sleep(7)
            input_box = driver.find_element_by_xpath('//*[@id="main"]/footer/div[1]/div[2]/div/div[2]')
            for ch in message:
                if ch == "\n":
                    ActionChains(driver).key_down(Keys.SHIFT).key_down(Keys.ENTER).key_up(Keys.ENTER).key_up(Keys.SHIFT).key_up(Keys.BACKSPACE).perform()
                else:
                    input_box.send_keys(ch)
            input_box.send_keys(Keys.ENTER)
            print("Message sent successfuly")
        except NoSuchElementException as exc:
            print(exc) # and/or other actions to recover
            print("Failed to send message")

targets = readContacts("./contacts-message.xlsx")

Is there anyone with a suggestion or who are willing to share their code?
Best wishes, folks. I am very new to Python and a farmer in Namibia, and I aim to send to separate message for each of my cattle buyers thanking them.
Emil Jung

Here is what I could find in terms of the html of the message box:

<div title="Type a message" role="textbox" class="_13NKt copyable-text selectable-text" contenteditable="true" data-tab="10" dir="ltr" spellcheck="true"></div>

Screen shot of Whatsapp

ABOVE, screenshot of Whatsapp - looking for the element.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

流心雨 2025-02-03 14:04:39

您是否尝试通过文本找到元素?

input_box = driver.find_element_by_xpath('//*[text()="Type a message"]')

或者,您可以使用contains()查找元素:

input_box = driver.find_element_by_xpath('//*[contains(@class, "copyable-text selectable-text")]'

Have you tried finding the element by the text?

input_box = driver.find_element_by_xpath('//*[text()="Type a message"]')

Or you could use contains() to find the element:

input_box = driver.find_element_by_xpath('//*[contains(@class, "copyable-text selectable-text")]'
痴情换悲伤 2025-02-03 14:04:39

好,很抱歉。如果我这样做,@Jfleach建议奏效了:

input_box = driver.find_elements(By.XPATH, '//*[text() = "Type a message"]')

当然,一个新的问题会弹出:

  File "C:\Users\aegju\.00. Python Projects\Shantanusk Whatsapp\Bulk Shanatanusk.py", line 64, in <module>
targets = readContacts("./contacts-message.xlsx")

  File "C:\Users\aegju\.00. Python Projects\Shantanusk Whatsapp\Bulk Shanatanusk.py", line 50, in readContacts
input_box.send_keys(ch)

AttributeError: 'list' object has no attribute 'send_keys'

或者是新事物,我应该发布一个新问题吗?

Ok, apologies. @jfleach suggestion worked if I do this:

input_box = driver.find_elements(By.XPATH, '//*[text() = "Type a message"]')

Now, of course, a new concern pops up:

  File "C:\Users\aegju\.00. Python Projects\Shantanusk Whatsapp\Bulk Shanatanusk.py", line 64, in <module>
targets = readContacts("./contacts-message.xlsx")

  File "C:\Users\aegju\.00. Python Projects\Shantanusk Whatsapp\Bulk Shanatanusk.py", line 50, in readContacts
input_box.send_keys(ch)

AttributeError: 'list' object has no attribute 'send_keys'

Or, being new, should I post a new question?

峩卟喜欢 2025-02-03 14:04:39

driver.find_element(
“ xpath”,'//*[@id =“ main”]/脚步/div [1]/div/div/span [2]/div/div/div [2]/div [1]/div/div/div/div/p') .send_keys(keys.enter)

driver.find_element(
"xpath", '//*[@id="main"]/footer/div[1]/div/span[2]/div/div[2]/div[1]/div/div/p').send_keys(Keys.ENTER)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文