Сообщение об ошибке: NoSuchElementException: Сообщение: такого элемента нет: невозможно найти элемент: {"method": "css selector", "selector": "._ 5qtp"} - PullRequest
2 голосов
/ 06 августа 2020

Я пробовал следующий код для автоматического обновления статуса на Facebook с помощью селена.

Я скопировал его с какого-то веб-сайта, чтобы узнать о селене. Здесь веб-драйвер не смог найти класс или идентификатор поля, в котором мы пишем статус.

Я даже искал его с помощью панели проверки, но я не получил никакого правильного идентификатора или класса и указанная выше ошибка. Пожалуйста, помогите мне!

Как мне найти XPath или идентификатор окна обновления статуса?

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.chrome.options import Options

import time
### login details ########################
username = "xxxxxxx@xxxxx.xxx"
pwd = "xxxxxxxxx"
##########################################

### what is on my mind ###################
msg = "hey there!"
##########################################

# initializing driver and loading web
chrome_path = r"chromedriver.exe"
options = Options()
options.add_argument("--disable-notifications")
driver = webdriver.Chrome(chrome_path, chrome_options=options)
driver.get("http://www.facebook.com/")
# end initializing

# start login
user_input = driver.find_element_by_xpath("""//*[@id="email"]""")
pwd_input = driver.find_element_by_xpath("""//*[@id="pass"]""")
user_input.send_keys(username)
pwd_input.send_keys(pwd)
pwd_input.send_keys(Keys.ENTER)
# end login

# writing msg
time.sleep(3)
first_what_is_on_my_mind_element = driver.find_element_by_class_name("_5qtp")
first_what_is_on_my_mind_element.click()
time.sleep(3)
second_what_is_on_my_mind_element = driver.switch_to.active_element
second_what_is_on_my_mind_element.send_keys(msg)
# end writing

# posting
buttons = driver.find_elements_by_tag_name('button')
for button in buttons:
    if 'Post' in button.text:
        button.click()
# end posting

1 Ответ

2 голосов
/ 08 августа 2020

Прежде всего, я предлагаю вам продолжить работу шаг за шагом в оболочке и протестировать ваш код в процессе.

import time
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.chrome.options import Options

#This part is for opening the webdriver with proxy (since FB is prohibited here!)
proxy="127.0.0.1:0000"
chrome_options=webdriver.ChromeOptions()
chrome_options.add_argument('--proxy-server=socks5://' + proxy)
driver=webdriver.Chrome(options=chrome_options)

# Let's open the FB and insert Username and Password:
driver.get("https://www.facebook.com")

# Give the username by copying the full XPath and send keys:
driver.find_element_by_xpath("/html/body/div[1]/div[3]/div/div/div/div/div[2]/form/table/tbody/tr[2]/td[1]/input").send_keys("Username") 

#Same for the Password:
driver.find_element_by_xpath("/html/body/div[1]/div[3]/div/div/div/div/div[2]/form/table/tbody/tr[2]/td[2]/input").send_keys("Password")

#Click the login button, you also can send Return key to password field:
driver.find_element_by_xpath("/html/body/div[1]/div[3]/div/div/div/div/div[2]/form/table/tbody/tr[2]/td[3]/label/input").click()

#Hitting the status bar:
driver.find_element_by_xpath("/html/body/div[1]/div/div/div[1]/div[3]/div/div/div[1]/div[1]/div/div[2]/div/div/div[3]/div/div[2]/div/div/div/div[1]/div/div[1]/div").click() 

#giving the status message:
driver.find_element_by_xpath("/html/body/div[1]/div/div/div[1]/div[4]/div/div/div[1]/div/div[2]/div/div/div/form/div/div[1]/div/div[2]/div[2]/div[1]/div[1]/div[1]/div/div/div/div/div[2]/div/div/div/div").send_keys("This is a test status from an automation :)")

#Hit the Post button:
driver.find_element_by_xpath("/html/body/div[1]/div/div/div[1]/div[4]/div/div/div[1]/div/div[2]/div/div/div/form/div/div[1]/div/div[2]/div[3]/div[2]/div").click()

#Enjoy the code :)

Я протестировал приведенный выше код, и он отлично работает. Вы можете найти Full-Xpath, как показано ниже: How to copy full XPath


Edited: First of all, forget about XPath for the Login page. Because it is relative to the browser condition. Instead, use the CSS Selector as below code: (It has also webdriver option for disabling notification which might solve the error of not finding status element)

import time
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.chrome.options import Options

username=str(input("Please enter your FB username:\n"))
password=str(input("Please enter your FB password:\n"))
proxy=str(input("Please enter your proxy:\n"))


#This part is for opening the webdriver with proxy (since FB is prohibited here!)
chrome_options=webdriver.ChromeOptions()
chrome_options.add_argument('--proxy-server=socks5://' + proxy)

# Making Notifications off automatically
prefs = {"profile.default_content_setting_values.notifications" : 2}
chrome_options.add_experimental_option("prefs",prefs)
driver=webdriver.Chrome(options=chrome_options)

# Let's open the FB and insert Username and Password:
driver.get("https://www.facebook.com")

# Give the username by copying the css_selector and send keys:
driver.find_element_by_css_selector("input#email.inputtext.login_form_input_box").send_keys(username)
#Same for the Password:
driver.find_element_by_css_selector("input#pass.inputtext.login_form_input_box").send_keys(username)

#Click the login button, you also can send Return key to password field:
driver.find_element_by_css_selector("label#loginbutton.login_form_login_button.uiButton.uiButtonConfirm").click()
#Hitting the status bar:
driver.find_element_by_xpath("/html/body/div[1]/div/div/div[1]/div[3]/div/div/div[1]/div[1]/div/div[2]/div/div/div[3]/div/div[2]/div/div/div/div[1]/div/div[1]/div").click() 

#giving the status message:
driver.find_element_by_xpath("/html/body/div[1]/div/div/div[1]/div[4]/div/div/div[1]/div/div[2]/div/div/div/form/div/div[1]/div/div[2]/div[2]/div[1]/div[1]/div[1]/div/div/div/div/div[2]/div/div/div/div").send_keys("This is a test status from an automation :)")

#Hit the Post button:
driver.find_element_by_xpath("/html/body/div[1]/div/div/div[1]/div[4]/div/div/div[1]/div/div[2]/div/div/div/form/div/div[1]/div/div[2]/div[3]/div[2]/div").click()


BTW, this is the way to select an element by mouse and in below picture you can see the CSS Selector name for Username field: (If you right-click on any element, while the inspector is on, you can find Copy>full XPath to copy the XPath)

Использование инструмента Inspector для отображения элемента селектора css

...