You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python Selenium中send_keys()仅发送字符串首字符的问题求助

Facebook自动发布仅输入首字符问题排查与解决

问题场景

使用Python Selenium实现Facebook自动发布图片功能,设置的caption为test加上爬取的话题标签,但发布后仅显示首字符t,其余内容丢失。

原始代码

#libraries

from selenium import webdriver
from selenium.webdriver.common.by import By
import selenium.webdriver.common.keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import bs4
from bs4 import BeautifulSoup as soup
from urllib.request import Request, urlopen
from time import sleep
import pyautogui


#fetching hashtags

def hashtags(hash_idea):
    url = 'http://best-hashtags.com/hashtag/' + hash_idea

    try:
        req = Request(url, headers={'User-Agent' : 'Mozilla/5.0'})
        page = urlopen(req, timeout=10)
        page_html = page.read()
        page.close()
        page_soup = soup(page_html, 'html.parser')
        result = page_soup.find('div',{'class':'tag-box tag-box-v3 margin-bottom-40'})
        tags = result.decode()
        start_index = tags.find('#')
        end_index = tags.find('</p1>')
        tags = tags[start_index:end_index]

        return tags
    except:
        print('Something went wrong While Fetching hashtags')


def login(username, password):

    try:
        url = 'https://facebook.com'
        driver.get(url)
        user = WebDriverWait(driver,20).until(EC.presence_of_element_located((By.NAME, 'email')))
        user.send_keys(username)
        pas = WebDriverWait(driver,20).until(EC.presence_of_element_located((By.NAME, 'pass')))
        pas.send_keys(password)
        login_btn = WebDriverWait(driver,20).until(EC.presence_of_element_located((By.NAME,'login')))
        login_btn.click()

    except:
        print('Something went wrong while login process')

def upload(img_path,caption):
    try:
        btn1 = WebDriverWait(driver,20).until(EC.presence_of_element_located((By.XPATH, '/html/body/div[1]/div[1]/div[1]/div/div[3]/div/div/div/div[1]/div[1]/div/div[2]/div/div/div/div[3]/div/div[2]/div/div/div/div[1]/div/div[1]')))
        btn1.click()

        btn2= WebDriverWait(driver,20).until(EC.presence_of_element_located((By.XPATH, '/html/body/div[1]/div[1]/div[1]/div/div[4]/div/div/div[1]/div/div[2]/div/div/div/form/div/div[1]/div/div/div/div[3]/div[1]/div[2]/div/div[1]/div/span/div/div/div[1]/div/div/div[1]/i')))
        btn2.click()

        btn3 = WebDriverWait(driver,20).until(EC.presence_of_element_located((By.XPATH, '/html/body/div[1]/div[1]/div[1]/div/div[4]/div/div/div[1]/div/div[2]/div/div/div/form/div/div[1]/div/div/div/div[2]/div[1]/div[2]/div/div[1]/div/div/div/div[1]/div/div/div/div[1]/div/i')))
        btn3.click()

        pyautogui.write(img_path)
        pyautogui.press('enter')

        cap = WebDriverWait(driver,20).until(EC.presence_of_element_located((By.XPATH, '/html/body/div[1]/div[1]/div[1]/div/div[4]/div/div/div[1]/div/div[2]/div/div/div/form/div/div[1]/div/div/div/div[2]/div[1]/div[1]/div[1]/div/div/div[1]')))
        cap.send_keys(caption)

        sleep(5) # this is mandatory while doing some thing with bot

        btn_post = WebDriverWait(driver,20).until(EC.presence_of_element_located((By.XPATH, '/html/body/div[1]/div[1]/div[1]/div/div[4]/div/div/div[1]/div/div[2]/div/div/div/form/div/div[1]/div/div/div/div[3]/div[2]/div/div/div[1]/div')))
        btn_post.click()
    except:
        print('Something Went Wrong While posting the image or video')

if __name__== "__main__":
    #turn for credentials, driver, and caption
    username = input('username : ')
    password = input('pass : ')
    img_path = 'pic1.jpg'
    hash_idea = 'covid'
    caption = 'test'  # if you want to
    caption = caption + '\n' + hashtags(hash_idea)
    driver = webdriver.Firefox(executable_path="C:/Users/Asus/Downloads/Compressed/geckodriver-v0.32.0-win64/geckodriver.exe")
    login(username,password)
    upload(img_path,caption)

解决办法

1. 修复话题标签函数的异常返回

当前hashtags函数出错时未返回有效字符串,会导致caption拼接成test\nNone,引发输入异常。修改函数添加默认返回:

def hashtags(hash_idea):
    url = 'http://best-hashtags.com/hashtag/' + hash_idea

    try:
        req = Request(url, headers={'User-Agent' : 'Mozilla/5.0'})
        page = urlopen(req, timeout=10)
        page_html = page.read()
        page.close()
        page_soup = soup(page_html, 'html.parser')
        result = page_soup.find('div',{'class':'tag-box tag-box-v3 margin-bottom-40'})
        tags = result.decode()
        start_index = tags.find('#')
        end_index = tags.find('</p1>')
        tags = tags[start_index:end_index]

        return tags
    except:
        print('Something went wrong While Fetching hashtags')
        return ""  # 添加空字符串作为默认返回

2. 替换不稳定的绝对XPATH定位

Facebook的DOM结构频繁变化,绝对XPATH极易失效,改用相对定位确保找到正确的输入框:

# 修改upload函数中的caption定位部分
cap = WebDriverWait(driver,20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, '[role="textbox"][aria-label*="caption"]')))
cap.click()  # 激活输入框
cap.clear()  # 清空默认内容
cap.send_keys(caption)

3. 替换pyautogui上传文件(更稳定)

pyautogui依赖系统焦点,容易导致后续输入焦点丢失,改用Selenium原生方法上传文件:

# 替换upload函数中pyautogui相关代码
# 移除btn3的点击和pyautogui操作,直接定位文件上传input
file_input = WebDriverWait(driver,20).until(EC.presence_of_element_located((By.CSS_SELECTOR, 'input[type="file"]')))
file_input.send_keys(img_path)  # 直接传入文件路径

4. 验证最终caption内容

在主函数中添加打印,确认caption的实际内容:

if __name__== "__main__":
    # ... 其他代码 ...
    caption = 'test'
    tags = hashtags(hash_idea)
    caption = caption + '\n' + tags
    print("最终要发布的内容:", repr(caption))  # 打印内容,检查是否有异常字符
    # ... 其他代码 ...

修改后的完整upload函数示例

def upload(img_path,caption):
    try:
        # 点击创建帖子按钮(改用相对定位)
        btn1 = WebDriverWait(driver,20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, '[aria-label="Create post"]')))
        btn1.click()

        # 点击添加图片按钮(改用相对定位)
        btn2= WebDriverWait(driver,20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, '[aria-label="Add Photo/Video"]')))
        btn2.click()

        # 直接上传文件
        file_input = WebDriverWait(driver,20).until(EC.presence_of_element_located((By.CSS_SELECTOR, 'input[type="file"]')))
        file_input.send_keys(img_path)

        # 定位并输入caption
        cap = WebDriverWait(driver,20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, '[role="textbox"][aria-label*="caption"]')))
        cap.click()
        cap.clear()
        cap.send_keys(caption)

        sleep(2)

        # 点击发布按钮
        btn_post = WebDriverWait(driver,20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, '[aria-label="Post"]')))
        btn_post.click()
    except Exception as e:
        print('发布出错:', str(e))

内容的提问来源于stack exchange,提问作者Raveen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.03 17:40:41