使用 Python 和 Selenium 抓取 Twitter 关注者

使用 Python 和 Selenium 抓取 Twitter 关注者

抓取数据示例

{
  "userId": "1710236730010349568",
  "isBlueVerified": false,
  "following": false,
  "canDm": false,
  "canMediaTag": true,
  "createdAt": "Fri Oct 06 10:13:15 +0000 2023",
  "defaultProfile": true,
  "defaultProfileImage": true,
  "description": "",
  "fastFollowersCount": 0,
  "favouritesCount": 456,
  "followersCount": 64,
  "friendCount": 7320,
  "hasCustomTimelines": false,
  "isTranslator": false,
  "listedCount": 0,
  "location": "",
  "mediaCount": 0,
  "name": "Paislie Dimitrov",
  "normalFollowersCount": 64,
  "pinnedTweetIdsStr": [],
  "possiblySensitive": false,
  "profileImageUrlHttps": "https://abs.twimg.com/sticky/default_profile_images/default_profile_normal.png",
  "profileInterstitialType": "",
  "username": "PaisliDimit",
  "statusesCount": 0,
  "translatorType": "none",
  "verified": false,
  "wantRetweets": false,
  "withheldInCountries": []
}

无需设置直接运行代码
我们的指南提供完整的即用代码以无缝抓取 Twitter 关注者数据。使用 Python 和 Selenium,自动化数据收集并有效捕捉性能日志,无需额外设置即可解锁 Twitter 的洞察!

步骤 1:设置环境

首先,安装 Selenium,这将允许我们自动化浏览器操作:

pip install -r requirements.txt

步骤 2:下载 ChromeDriver

您可以从这里找到相应的 ChromeDriver 下载 ChromeDriver

步骤 3:设置 Chrome 选项

self.options = webdriver.ChromeOptions()
user_agent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/110.0.0.0 Safari/537.36'
self.options.add_argument(f'user-agent={user_agent}')
self.options.add_argument('--disable-gpu')
self.options.add_argument('--no-sandbox')
self.options.add_argument('--disable-dev-shm-usage')
self.options.add_argument(f"--remote-debugging-port={remote_debugging_port}")

js_script_name = modify_random_canvas_js()
self.browser = self.get_browser(script_files=[js_script_name], record_network_log=True, headless=True)

步骤 4:访问目标页面

self.browser.switch_to.new_window('tab')
url= 'https://x.com/1_usd_promotion/verified_followers'
self.browser.get(url=url)

time.sleep(2)

exist_entry_id = []

self.get_network(exist_entry_id, result_list)

print(f'tweet result length = {len(result_list)}')

步骤 5:获取浏览器性能日志

performance_log = self.browser.get_log("performance")
for packet in performance_log:
    msg = packet.get("message")
    message = json.loads(packet.get("message")).get("message")
    packet_method = message.get("method")
    if "Network" in packet_method and 'Following' in msg:
        request_id = message.get("params").get("requestId")
        resp = self.browser.execute_cdp_cmd('Network.getResponseBody', {'requestId': request_id})

步骤 6:从响应中提取数据

body = resp.get("body")
body = json.loads(body)
instructions = body['data']['user']['result']['timeline']['timeline'].get('instructions', None)
if not instructions:
    continue
for instruction in instructions:
    entries = instruction.get('entries', None)

步骤 7:重要注意事项

常见问题:FAQ

  • Q: 什么是网页抓取?

    网页抓取就像使用特殊工具自动从网站收集信息。想象一个机器人帮助从页面上收集数据,这样您就不必手动进行。在这种情况下,我们专注于使用 Python 和 Selenium 抓取 Twitter 数据。

  • Q: 如何开始抓取 Twitter 数据?

    要开始抓取 Twitter 数据,您首先需要设置您的计算机。这包括安装名为 Selenium 的软件,它帮助您控制网页浏览器。然后,您下载 ChromeDriver,这是一种允许 Selenium 与 Google Chrome 一起工作的辅助工具。

  • Q: 什么是 ChromeDriver,为什么我需要它?

    ChromeDriver 就像 Selenium 和 Google Chrome 的翻译器。它帮助 Selenium 理解如何与 Chrome 浏览器互动。您需要它,以便 Selenium 可以自动化点击按钮或在 Twitter 上输入信息等操作。

  • Q: 抓取中的性能日志是什么?

    性能日志就像记录您网页抓取过程中所有事情的日记。它记录您抓取工具(Selenium)和 Twitter 页面之间的所有数据交换,帮助您了解您的程序正在发送什么请求。

  • Q: 抓取 Twitter 前我应考虑什么?

    在抓取 Twitter 之前,您需要登录您的 Twitter 账户并获取一个称为 auth_token 的东西,以证明您有权访问 Twitter 的数据。此外,要小心遵循 Twitter 的规则,以免被封锁。

  • Q: 如何避免在抓取时被封锁?

    为了避免被封锁,请确保在请求之间引入延迟,旋转代理,并避免在短时间内对 Twitter 的服务器施加过多请求。