如何用Selenium Python在Facebook广告库搜索框输入文本并提交
解决Selenium无法提交Meta Ads Library搜索的问题
Meta Ads Library的搜索组件通常没有包裹在传统的<form>标签中,所以你通过form.submit()的方式会找不到元素而失败。可以用以下两种替代方案完成搜索提交:
方案1:模拟回车键提交
直接在输入框按下回车键,和手动操作逻辑一致,兼容性更强:
from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.keys import Keys # A function to utilize Selenium to crawl the Meta Ads Library and grab needed ads links def get_facebook_ads(): try: # Initialize the browser and navigate to the page browser = webdriver.Chrome(executable_path="C:\\Users\\S\\OneDrive\\Programming\\Learning-Projects\\chromedriver.exe") browser.get("https://www.facebook.com/ads/library/?active_status=active&ad_type=all&country=ALL&q=%22%20%22&sort_data[direction]=desc&sort_data[mode]=relevancy_monthly_grouped&search_type=keyword_exact_phrase&media_type=all&content_languages[0]=en") # Enter a keyword in the search box search_box = WebDriverWait(browser, 10).until(EC.presence_of_element_located((By.XPATH, "//input[@placeholder='Search by keyword or advertiser']"))) search_box.send_keys("dog") # 模拟回车键提交搜索 search_box.send_keys(Keys.ENTER) # 后续可添加爬取广告链接的逻辑 except Exception as e: print(e) if 'browser' in locals(): browser.quit()
方案2:直接定位搜索按钮点击
如果回车键提交无效,可以直接定位页面上的搜索按钮(通常是放大镜图标或标注"Search"的按钮),执行点击操作:
# 替换方案1中的回车键代码为以下内容 search_button = WebDriverWait(browser, 10).until(EC.element_to_be_clickable((By.XPATH, "//button[@aria-label='Search']"))) search_button.click()
注意:如果上述XPath找不到按钮,需通过浏览器开发者工具查看按钮的实际属性(如class、aria-label等),调整XPath表达式。
额外注意事项
- 确保导入所有必要的Selenium模块,尤其是
Keys模块 - 异常处理中增加了
browser存在性检查,避免未初始化时调用quit()报错
内容的提问来源于stack exchange,提问作者Saad.A
相关产品推荐
相关产品推荐

