用selenium实现微博抽奖

前置准备

1.准备Python环境,安装selenium(运行命令:pip install selenium==4.16.0);

2.准备谷歌浏览器以及与浏览器同版本的webdriver(driver下载地址),将driver文件与此.py文件放在一起,并将浏览器chrome.exe路径赋给option.binary_location。

代码

import random
import time

from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait

option = Options()
option.binary_location = r'.\doc\Chrome\Application\chrome.exe'
choujiang_url = 'https://www.weibo.com/5692100100/NC99xE0pd#repost'

# 打开浏览器
with webdriver.Chrome(option) as driver:
    driver.get('https://weibo.com/')
    print('手动登录')
    WebDriverWait(driver, 1e5).until(lambda d: d.find_elements(By.XPATH,
                                                               '//div[@]/img'))  # 寻找登入标记
    driver.get(choujiang_url)  # 抽奖微博链接
    user_set = set()  # 使用set集合储存转发用户,避免重复获取
    user_list_tmp = []
    while True:
        user_list_tmp = driver.find_elements(By.XPATH,  '//*[@id="scroller"]/div[1]/div//div/a[@usercard]')
        user_list_tmp = [tuple([e.accessible_name, e.get_attribute('href')]) for e in user_list_tmp]  # 用户名与主页链接
        print('此页获取的用户名:', [_[0] for _ in user_list_tmp])
        user_set.update(user_list_tmp)  # 录入集合
        driver.execute_script("window.scrollTo(0, window.scrollY + 300)")  # 页面下拉,刷新用户
        if driver.find_elements(By.XPATH, '//div[starts-with(@class,"Bottom_text_") '
                                          'and contains(text(), "没有更多内容了")]'):  # 获取完
            break
    driver.minimize_window()
    input(f'共获取{len(user_set)}位转发用户,按回车开始抽取')
    choujiang_list = list(user_set)  # 转储到list方便抽取
    zhongjiang_list = []  # 中奖名单
    time.sleep(random.random())  # 增加random的不确定性
    random.seed(time.time())
    for _ in range(3):  # 抽3人
        time.sleep(3)  # 停顿一下
        zhongjiang = random.choice(choujiang_list)  # 随机获取一位作为中奖者
        zhongjiang_list.append(zhongjiang)  # 记录中奖名单
        choujiang_list.remove(zhongjiang)  # 移除,以免重复抽到
        print(f'已抽取{_ + 1}名中奖者')
    time.sleep(1)
    print('中奖名单:', zhongjiang_list)
    # 打开每个中奖者主页
    for u in zhongjiang_list:
        driver.execute_script(f"window.open('{u[1]}','_blank');")
    time.sleep(1)
    driver.maximize_window()
    input('结束')

注意:微博页面时常变动,正式使用前需要先测试,xpath可能需要修改。

本文来自网络,不代表协通编程立场,如若转载,请注明出处:https://www.net2asp.com/570b4568ae.html