如何使用Python Selenium WebDriver打印所有已加入的Facebook群组
Python+Selenium获取Facebook已加入全部群组实现方案
原代码存在3个核心问题导致无法稳定拿到全部群组:
- 依赖Facebook动态生成的随机类名定位元素,平台前端更新后定位逻辑就会失效
- 没有处理群组列表的懒加载逻辑,只能拿到当前可视区域内的部分群组
- 使用了Selenium 4.0+版本已弃用的
find_element_by_*系列API,新版本运行会直接报错
以下是修正后可稳定运行的代码:
import time from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.common.action_chains import ActionChains # 你的chromedriver路径 PATH = "C://Program Files (x86)//Chrome Driver//chromedriver.exe" chrome_options = webdriver.ChromeOptions() # 禁用通知、避免被检测为自动化工具 chrome_options.add_argument("--disable-notifications") chrome_options.add_argument("--disable-blink-features=AutomationControlled") chrome_options.add_experimental_option("excludeSwitches", ["enable-automation"]) chrome_options.add_experimental_option('useAutomationExtension', False) driver = webdriver.Chrome(executable_path=PATH, options=chrome_options) driver.maximize_window() driver.get("https://www.facebook.com") driver.implicitly_wait(10) # 登录部分,建议直接用已登录的Chrome用户目录跳过,避免风控 driver.find_element(By.XPATH, "//input[@id='email']").send_keys("你的账号") driver.find_element(By.XPATH, "//input[@id='pass']").send_keys("你的密码") driver.find_element(By.XPATH, "//button[@name='login']").click() time.sleep(3) # 进入群组页面 driver.get("https://www.facebook.com/groups/feed/") time.sleep(3) # 滚动加载全部已加入群组,直到没有新内容加载 last_group_count = 0 while True: # 定位已加入群组的名称元素,中文界面用「你加入的群组」,英文界面替换为"Groups you've joined" groups = driver.find_elements(By.XPATH, '//div[contains(text(),"你加入的群组")]/following-sibling::div//span[contains(@class,"oo9gr5id")]') current_group_count = len(groups) if current_group_count == last_group_count: break last_group_count = current_group_count # 滚动到当前最后一个群组位置触发加载 driver.execute_script("arguments[0].scrollIntoView(false);", groups[-1]) time.sleep(2) # 打印结果 print(f"已加入群组总数:{len(groups)}") for index, group in enumerate(groups, 1): print(f"{index}. {group.text}") driver.quit()
注意事项
- 建议提前在本地Chrome登录好Facebook,通过加载用户配置文件的方式启动浏览器,避免每次输入账号密码触发风控,配置方式为在Chrome启动参数中添加
chrome_options.add_argument(r'user-data-dir=C:\Users\你的系统用户名\AppData\Local\Google\Chrome\User Data') - 若界面语言为英文,将定位逻辑中的「你加入的群组」替换为对应英文文本即可
- 不要短时间内多次重复运行,避免Facebook判定账号异常触发限制
内容的提问来源于stack exchange,提问作者Mohibur_Cou
相关产品推荐
相关产品推荐

