NameError:name' attach_and_send_screenshot'未在python

时间:2018-06-16 11:23:15

标签: python python-3.x selenium webdriver selenium-chromedriver

用于通过硒发送附件,使用self._attach_and_send_screenshot()功能进行自动生成。

扫描QR码后输入任何内容 Traceback(最近一次调用最后一次):   文件" wht.py",第21行,in     attach_and_send_screenshot() NameError:name' attach_and_send_screenshot'未定义

from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException, StaleElementReferenceException, ElementNotVisibleException
from urllib.parse import quote_plus

driver = webdriver.Chrome()
driver.get('https://web.whatsapp.com/')

all_names = ['Anas Cse']
msg = 'testing'
count = 1

input('Enter anything after scanning QR code')

for name in all_names:
    user = driver.find_element_by_xpath('//span[@title = "{}"]'.format(name))
    user.click()

    msg_box = driver.find_element_by_class_name('_2S1VP')

    for i in range(count):
         self._attach_and_send_screenshot()
#         msg_box.send_keys(msg)
#         button = driver.find_element_by_class_name('_2lkdt')
#         button.click()



def _attach_and_send_screenshot(self):
    # TODO - ElementNotVisibleException - this shouldn't happen but when would it

    # local variables for x_path elements on browser
    attach_xpath = '//*[@id="main"]/header/div[3]/div/div[2]/div'
    send_file_xpath = '//*[@id="app"]/div/div/div[1]/div[2]/span/div/span/div/div/div[2]/span[2]/div/div'

    if self.attachment_type == "img":
            attach_type_xpath = '//*[@id="main"]/header/div[3]/div/div[2]/span/div/div/ul/li[1]/input'
    elif self.attachment_type == "cam":
        attach_type_xpath = '//*[@id="main"]/header/div[3]/div/div[2]/span/div/div/ul/li[2]/button'
    elif self.attachment_type == "doc":
        attach_type_xpath = '//*[@id="main"]/header/div[3]/div/div[2]/span/div/div/ul/li[3]/input'

    try:
        # open attach menu
        attach_btn = driver.find_element_by_xpath(attach_xpath)
        attach_btn.click()

        # Find attach file btn and send screenshot path to input
        time.sleep(1)
        attach_img_btn = driver.find_element_by_xpath(attach_type_xpath)

            # TODO - might need to click on transportation mode if url doesn't work
        attach_img_btn.send_keys(os.getcwd() + "/screenshot.png")           # get current script path + img_path
        time.sleep(1)
        send_btn = driver.find_element_by_xpath(send_file_xpath)
        send_btn.click()

                # close attach menu
        time.sleep(1)
        attach_btn = driver.find_element_by_xpath(attach_xpath)
        attach_btn.click()

    except (NoSuchElementException, ElementNotVisibleException) as e:
        print(str(e))
        send_message((str(e)))
        send_message("Bot failed to retrieve search content, try again...")

def send_message(msg):
    whatsapp_msg = driver.find_element_by_class_name('_2S1VP')
    whatsapp_msg.send_keys(msg)
    whatsapp_msg.send_keys(Keys.ENTER)

1 个答案:

答案 0 :(得分:0)

在主逻辑之前移动函数定义。您正在尝试调用尚未定义的函数