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

使用Python爬取Twitter页面时持续返回“JavaScript is not available”问题求助

解决Python爬取Twitter返回“JavaScript is not available”的问题

问题原因

你在Chrome浏览器启用JavaScript没用的核心原因是:requests库发送的是纯HTTP请求,它没有浏览器内核,不会执行JavaScript,也不会模拟正常浏览器的请求特征(比如正确的User-Agent、Cookie、渲染行为等)。Twitter的反爬机制识别出这不是正常的浏览器访问,因此返回“JavaScript is not available”的提示,和你本地Chrome的设置完全无关。

解决方案

方案1:使用Selenium模拟真实浏览器

Selenium可以驱动浏览器加载页面、执行JavaScript,完全模拟用户访问行为,绕过这类反爬检测。

步骤:

  1. 安装Selenium:pip install selenium
  2. 下载对应版本的ChromeDriver(和你的Chrome版本匹配)
  3. 运行以下代码:
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from bs4 import BeautifulSoup
import time

# 配置Chrome选项,模拟正常浏览器
chrome_options = Options()
chrome_options.add_argument("--headless=new")  # 无头模式,不弹出浏览器窗口
chrome_options.add_argument("--disable-gpu")
chrome_options.add_argument("user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36")

# 初始化浏览器驱动
driver = webdriver.Chrome(options=chrome_options)
target_url = "https://twitter.com/search?q=%23developer%20advocate&src=typed_query&f=user"

try:
    driver.get(target_url)
    time.sleep(3)  # 等待页面完全加载(可替换为显式等待更可靠)
    
    # 获取渲染后的页面源码
    page_source = driver.page_source
    soup = BeautifulSoup(page_source, "lxml")
    
    # 提取用户信息示例
    user_cells = soup.find_all("div", attrs={"data-testid": "UserCell"})
    for cell in user_cells:
        user_info = cell.find("div", attrs={"data-testid": "UserName"}).get_text(strip=True)
        print(user_info)
finally:
    driver.quit()  # 关闭浏览器

方案2:使用Twitter官方API(合规稳定)

网页爬取属于非合规访问,容易触发反爬甚至账号封禁。使用Twitter官方API是更稳妥的方式,需要先申请开发者账号,获取API密钥。

示例代码(需安装tweepy:pip install tweepy):

import tweepy

# 替换为你的开发者密钥
API_KEY = "你的API_KEY"
API_SECRET = "你的API_SECRET"
ACCESS_TOKEN = "你的ACCESS_TOKEN"
ACCESS_TOKEN_SECRET = "你的ACCESS_TOKEN_SECRET"

# 认证并初始化API
auth = tweepy.OAuthHandler(API_KEY, API_SECRET)
auth.set_access_token(ACCESS_TOKEN, ACCESS_TOKEN_SECRET)
api = tweepy.API(auth)

# 搜索带指定标签的用户
for user in tweepy.Cursor(api.search_users, q="#developer advocate").items(10):
    print(f"用户名: @{user.screen_name}, 昵称: {user.name}")

注意事项

  • 模拟浏览器时,不要频繁发送请求,建议添加随机延迟,避免IP被封禁
  • 官方API有请求频率限制,但完全符合Twitter的使用规则,不会触发反爬
  • 也可以选择Playwright替代Selenium,它的API更简洁,支持多浏览器(Chrome、Firefox、Edge等)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 02:30:40