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

如何使用Selenium获取Twitter引用转推的推文URL?

获取Twitter引用推文URL的解决方案

Twitter采用React动态渲染页面,引用推文的链接不会直接在HTML的href属性中暴露,可通过以下方式获取:

核心思路

  1. 用稳定定位替代绝对XPath:优先使用Twitter官方提供的data-testid属性定位元素,避免页面布局变化导致定位失效。引用推文容器的data-testid值为quoted-tweet,内部嵌套的a标签对应跳转链接。
  2. 添加显式等待:动态页面需等待元素加载完成后再操作,避免出现元素未找到的错误。
  3. 提取链接属性:通过get_attribute("href")或执行JavaScript获取链接地址。

修改后的完整代码

from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

# 启动Chrome浏览器
try:
    chrome_options = webdriver.ChromeOptions()
    driver = webdriver.Chrome(service=Service(), options=chrome_options)
except Exception as e:
    print(e)

# 登录Twitter
driver.get("https://twitter.com")

login = "......"
pw = "......"

wait = WebDriverWait(driver, 10)

# 点击登录按钮
login_btn = wait.until(EC.element_to_be_clickable((By.XPATH, '//*[@id="react-root"]/div/div/div[2]/main/div/div/div[1]/div[1]/div/div[3]/div[5]/a')))
login_btn.click()

# 输入账号
username_input = wait.until(EC.visibility_of_element_located((By.XPATH, '//*[@id="layers"]/div[2]/div/div/div/div/div/div[2]/div[2]/div/div/div[2]/div[2]/div/div/div/div[5]/label')))
username_input.send_keys(login)

# 点击下一步
next_btn = wait.until(EC.element_to_be_clickable((By.XPATH, '//*[@id="layers"]/div[2]/div/div/div/div/div/div[2]/div[2]/div/div/div[2]/div[2]/div/div/div/div[6]')))
next_btn.click()

# 输入密码
password_input = wait.until(EC.visibility_of_element_located((By.XPATH, '//*[@id="layers"]/div[2]/div/div/div/div/div/div[2]/div[2]/div/div/div[2]/div[2]/div[1]/div/div/div[3]/div/label')))
password_input.send_keys(pw)

# 提交登录
submit_login = wait.until(EC.element_to_be_clickable((By.XPATH, '//*[@id="layers"]/div[2]/div/div/div/div/div/div[2]/div[2]/div/div/div[2]/div[2]/div[2]/div/div[1]/div/div/div')))
submit_login.click()

# 打开目标推文
driver.get("https://twitter.com/JoeBiden/status/1712487592740978801")

# 获取引用推文URL
quoted_link = wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, '[data-testid="quoted-tweet"] a')))
quoted_url = quoted_link.get_attribute("href")
print("引用推文URL:", quoted_url)

# 关闭浏览器
driver.quit()

备用方案

如果上述方法无法获取href,可通过JavaScript提取链接:

quoted_url = driver.execute_script("return arguments[0].href;", quoted_link)

内容的提问来源于stack exchange,提问作者François M.

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 07:30:08