首页 > 解决方案 > Selenium 无法在我的 Facebook 页面上的“发帖”窗口上写字

问题描述

我正在制作一个 python 脚本来在我的 Facebook 搜索页面上进行自动发布。但我不能在“发帖”的小窗口上写字。 发帖

我已经尝试过更改 xpath,但我无法让它工作。我看到了另一个代码,但 xhpx_message_text/xhpc_message 不起作用。我的实际代码是...

browser.get("https://www.facebook.com/This-frutas-107314187288001/")
sleep(5)
post_box=browser.find_element_by_xpath('/html/body/div[1]/div[3]/div[1]/div/div/div[2]/div[2]/div[2]/div/div[2]/div[2]/div/div[1]/div/div[2]/div/div[2]/div[1]/div[2]/div/div/div[2]/div/div/div/div/div/div/div[1]/div/div[1]/div/div[2]/div/div/div')

post_box.click()

sleep(2)
post_box=browser.find_element_by_xpath('/html/body/div[1]/div[3]/div[1]/div/div/div[2]/div[2]/div[2]/div/div[2]/div[2]/div/div[1]/div/div[2]/div/div[2]/div[1]/div[2]/div/div/div[2]/div[1]/div/div/div/div[2]/div/div[1]/div/div[1]/div[1]/div[2]/div/div/div/div/div/div/div')

post_box.send_keys("This is an automated post.")

我的实际输出是...

Traceback (most recent call last):
  File "C:\Users\oyane\Downloads\facecook-selenium-master\login-facebook.py", line 30, in <module>
    post_box.send_keys("This is an automated post.")
  File "C:\Users\oyane\AppData\Local\Programs\Python\Python37-32\lib\site-packages\selenium\webdriver\remote\webelement.py", line 479, in send_keys
    'value': keys_to_typing(value)})
  File "C:\Users\oyane\AppData\Local\Programs\Python\Python37-32\lib\site-packages\selenium\webdriver\remote\webelement.py", line 633, in _execute
    return self._parent.execute(command, params)
  File "C:\Users\oyane\AppData\Local\Programs\Python\Python37-32\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 321, in execute
    self.error_handler.check_response(response)
  File "C:\Users\oyane\AppData\Local\Programs\Python\Python37-32\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 242, in check_response
    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.ElementNotInteractableException: Message: Element <div class="_3nd0"> is not reachable by keyboard

标签: pythonseleniumselenium-webdriver

解决方案


  1. 我认为您的方法不会奏效,因为 Selenium 每次都会运行一个干净的浏览器会话,所以很可能您必须先登录您的 Facebook 帐户才能打开任何页面
  2. 使用硬编码sleeps是某种形式的性能反模式,您应该改用显式等待
  3. 使用绝对 XPath 定位器不是最佳选择,因为定位器非常脆弱,因此对标记更改很敏感。因此,我建议使用相对 XPath 定位器,例如“您的想法”输入字段的相关XPath 表达式将类似于:

    //textarea[contains(@aria-label, 'on your mind')]
    
  4. 假设以上所有内容,我认为您最终应该得到以下结果:

    WebDriverWait(driver, 10).until(expected_conditions.element_to_be_clickable((By.ID, "email"))).send_keys(
        "your@email.here")
    WebDriverWait(driver, 10).until(expected_conditions.element_to_be_clickable((By.ID, "pass"))).send_keys("your_password_here")
    WebDriverWait(driver, 10).until(
        expected_conditions.element_to_be_clickable((By.XPATH, "//input[@value='Log In']"))).click()
    
    WebDriverWait(driver, 10).until(expected_conditions.element_to_be_clickable(
        (By.XPATH, "//textarea[contains(@aria-label, 'on your mind')]"))).send_keys("your post text")
    

推荐阅读