Python Selenium 脚本:爬取推特大运会新闻 - 2023年7月1日至23日
以下是使用Selenium编写的Python脚本,用于爬取推特上关键词为"大运会"的新闻内容、时间、账号以及点赞、浏览、排列数量。脚本将搜索日期限定在2023年7月1日至2023年7月23日之间。\n\npython\nfrom selenium import webdriver\nfrom selenium.webdriver.common.keys import Keys\nimport time\n\n# 设置Chrome浏览器的驱动路径\ndriver_path = 'path_to_chromedriver'\n\n# 实例化一个Chrome浏览器对象\ndriver = webdriver.Chrome(executable_path=driver_path)\n\n# 打开推特网站\ndriver.get("https://twitter.com")\n\n# 等待页面加载\ntime.sleep(2)\n\n# 找到搜索输入框并输入关键词\nsearch_box = driver.find_element_by_xpath('//input[@aria-label="Search query"]')\nsearch_box.send_keys("(大运会 OR FISU) until:2023-07-23 since:2023-07-01")\nsearch_box.send_keys(Keys.RETURN)\n\n# 等待搜索结果加载\ntime.sleep(2)\n\n# 模拟向下滚动页面,加载更多推文\nbody = driver.find_element_by_tag_name('body')\nfor _ in range(10):\n body.send_keys(Keys.PAGE_DOWN)\n time.sleep(1)\n\n# 找到所有推文的元素\ntweets = driver.find_elements_by_xpath('//div[@data-testid="tweet"]')\n\n# 遍历每个推文并提取所需信息\nfor tweet in tweets:\n try:\n # 提取时间\n timestamp = tweet.find_element_by_xpath('.//time').get_attribute('datetime')\n \n # 提取账号\n account = tweet.find_element_by_xpath('.//span[contains(@class, "username")]').text\n \n # 提取点赞、浏览、排列数量\n stats = tweet.find_element_by_xpath('.//div[@data-testid="like"]//span[@class="css-901oao css-16my406 r-poiln3 r-bcqeeo r-qvutc0"]')\n likes = stats.get_attribute('innerHTML')\n \n stats = tweet.find_element_by_xpath('.//div[@data-testid="retweet"]//span[@class="css-901oao css-16my406 r-poiln3 r-bcqeeo r-qvutc0"]')\n retweets = stats.get_attribute('innerHTML')\n \n stats = tweet.find_element_by_xpath('.//div[@data-testid="reply"]//span[@class="css-901oao css-16my406 r-poiln3 r-bcqeeo r-qvutc0"]')\n replies = stats.get_attribute('innerHTML')\n \n # 提取新闻内容\n 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\n \n # 打印提取的信息\n print("时间:", timestamp)\n print("账号:", account)\n print("点赞数量:", likes)\n print("浏览数量:", retweets)\n print("排列数量:", replies)\n print("新闻内容:", content)\n print("=====================================")\n except:\n continue\n\n# 关闭浏览器\ndriver.quit()\n\n\n请确保将path_to_chromedriver替换为您本地Chrome浏览器驱动的路径。此外,您还需要安装Selenium库和Chrome浏览器驱动。
原文地址: https://www.cveoy.top/t/topic/pY7x 著作权归作者所有。请勿转载和采集!