我正在尝试使用 Selenium(使用 Python)提取 Twitter 上每条特定推文的链接。例如,假设我正在查看 https://twitter.com/search?q=from%3A%40POTUS&src=typed_query&f=live
每条推文的右下角都有这个箭头按钮
单击后,它会显示另外 3 个选项,第一个是“复制链接”选项,用于将推文的直接链接保存到剪贴板。
如何指示 Selenium 单击该箭头 + 复制链接,然后保存页面上所有推文的 URL?
目前我的代码看起来像这样:
from selenium import webdriver
driver = webdriver.Firefox()
driver.get("https://twitter.com/search?q=from%3A%40POTUS&src=typed_query&f=live")
links = []
articles = driver.find_elements(By.XPATH, '//article[@data-testid = "tweet"]')
for article in articles:
link = article.find_element(By.XPATH, './/svg').click() # cant figure it out
links.append(link)
您无需单击图标即可获取推文链接。
Twit 本身在一个元素内包含该链接。
该元素的定位器是 css 选择器
[data-testid=User-Name] a[role=link][href*=status]
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
chrome_options = Options()
chrome_options.add_argument("--disable-gpu")
driver = webdriver.Chrome(options=chrome_options)
driver.get("https://twitter.com/search?q=from%3A%40POTUS&src=typed_query&f=live")
# login there
links = []
wait = WebDriverWait(driver, 10)
hrefs = wait.until(EC.presence_of_all_elements_located((By.CSS_SELECTOR, '[data-testid=User-Name] a[role=link][href*=status]')))
for href in hrefs:
link = href.get_attribute('href')
links.append(link)
print(link)