以下是使用Selenium编写的Python脚本,用于爬取推特上关键词为"大运会"的新闻内容、时间、账号以及点赞、浏览、排列数量。脚本将搜索日期限定在2023年7月1日至2023年7月23日之间。

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import time

# 设置Chrome浏览器的驱动路径
driver_path = 'path_to_chromedriver'

# 实例化一个Chrome浏览器对象
driver = webdriver.Chrome(executable_path=driver_path)

# 打开推特网站
driver.get("https://twitter.com")

# 等待页面加载
time.sleep(2)

# 找到搜索输入框并输入关键词
search_box = driver.find_element_by_xpath('//input[@aria-label="Search query"]')
search_box.send_keys("(大运会 OR FISU) until:2023-07-23 since:2023-07-01")
search_box.send_keys(Keys.RETURN)

# 等待搜索结果加载
time.sleep(2)

# 模拟向下滚动页面,加载更多推文
body = driver.find_element_by_tag_name('body')
for _ in range(10):
    body.send_keys(Keys.PAGE_DOWN)
    time.sleep(1)

# 找到所有推文的元素
tweets = driver.find_elements_by_xpath('//div[@data-testid="tweet"]')

# 遍历每个推文并提取所需信息
for tweet in tweets:
    try:
        # 提取时间
        timestamp = tweet.find_element_by_xpath('.//time').get_attribute('datetime')
        
        # 提取账号
        account = tweet.find_element_by_xpath('.//span[contains(@class, "username")]').text
        
        # 提取点赞、浏览、排列数量
        stats = tweet.find_element_by_xpath('.//div[@data-testid="like"]//span[@class="css-901oao css-16my406 r-poiln3 r-bcqeeo r-qvutc0"]')
        likes = stats.get_attribute('innerHTML')
        
        stats = tweet.find_element_by_xpath('.//div[@data-testid="retweet"]//span[@class="css-901oao css-16my406 r-poiln3 r-bcqeeo r-qvutc0"]')
        retweets = stats.get_attribute('innerHTML')
        
        stats = tweet.find_element_by_xpath('.//div[@data-testid="reply"]//span[@class="css-901oao css-16my406 r-poiln3 r-bcqeeo r-qvutc0"]')
        replies = stats.get_attribute('innerHTML')
        
        # 提取新闻内容
        content = tweet.find_element_by_xpath('.//div[@class="css-901oao r-1fmj7o5 r-1qd0xha r-a023e6 r-o7ynqc r-16dba41 r-ad9z0x r-bcqeeo r-bnwqim r-qvutc0"]//span').text
        
        # 打印提取的信息
        print("时间:", timestamp)
        print("账号:", account)
        print("点赞数量:", likes)
        print("浏览数量:", retweets)
        print("排列数量:", replies)
        print("新闻内容:", content)
        print("=====================================")
    except:
        continue

# 关闭浏览器
driver.quit()

请确保将path_to_chromedriver替换为您本地Chrome浏览器驱动的路径。此外,您还需要安装Selenium库和Chrome浏览器驱动

用selenium写一个爬写推特新闻的python脚本搜索关键词是大运会爬取新闻内容时间、账号和点赞、浏览、排列数量搜索大运会 OR FISU until2023-07-23 since2023-07-01爬取完全

原文地址: https://www.cveoy.top/t/topic/igPX 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录