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

使用Selenium抓取Instagram设置页关注请求列表遇到的问题

问题原因&解决方案
  • 你用的class名-utLF是Instagram前端动态生成的随机类名,会随版本更新、页面刷新甚至会话变化失效,完全不适合作为定位依据。
  • find_elements_by_class_name返回的是元素列表,你直接对列表调用.text属性本身就是错误写法,不可能拿到返回值。
  • 硬sleep无法保证元素完全渲染完成,可能你定位的时候元素还没加载到DOM里,自然拿空。
  • 部分场景下Selenium内置的.text属性只能拿到视口内可见元素的文本,未出现在可视区域的元素文本会返回空。

修复后代码示例

from time import sleep
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By

#user_info
user = 'xxx'
password = 'xxx'

#login
bot = webdriver.Firefox()
bot.get('https://instagram.com')
sleep(2)
username_input = bot.find_element_by_xpath('/html/body/div[1]/section/main/article/div[2]/div[1]/div/form/div/div[1]/div/label/input')
sleep(1)
username_input.send_keys(user)
sleep(1)
password_input = bot.find_element_by_xpath('/html/body/div[1]/section/main/article/div[2]/div[1]/div/form/div/div[2]/div/label/input')
sleep(1)
password_input.send_keys(password)
sleep(1)
bot.find_element_by_xpath('/html/body/div[1]/section/main/article/div[2]/div[1]/div/form/div/div[3]/button/div').click()
sleep(3)

#try_to_scraping_requested_profile
bot.get('https://instagram.com/accounts/access_tool/current_follow_requests')
sleep(2)
viewmore = 0
while viewmore <4:
    # 新增显式等待,确保加载按钮可点击后再操作
    load_btn = WebDriverWait(bot, 10).until(
        EC.element_to_be_clickable((By.XPATH, '/html/body/div[1]/div/div/section/main/div/article/main/button'))
    )
    load_btn.click()
    viewmore += 1
    sleep(1)

requestlist =[]
# 改用稳定的XPath定位所有用户名a标签,不使用动态类名
users = WebDriverWait(bot, 10).until(
    EC.presence_of_all_elements_located((By.XPATH, '//main//div[@role="article"]//a'))
)

# 用textContent属性获取文本,规避视口可见性限制
for user in users :
    uname = user.get_attribute('textContent').strip()
    if uname:
        requestlist.append(uname)
print(requestlist)

补充说明

如果上述XPath定位失效,可以手动打开浏览器开发者工具,找到关注请求列表用户名标签的共同稳定上级节点,调整定位表达式即可,核心是不要使用前端随机生成的动态类名做定位依据。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 07:36:03