鱼C论坛

 找回密码
 立即注册
查看: 82|回复: 1

用selenium自动登录虎牙账号

[复制链接]
发表于 昨天 16:28 | 显示全部楼层 |阅读模式
50鱼币
from random import choice
from time import sleep
from selenium import webdriver
from selenium.webdriver import ActionChains
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.service import Service


def parse_data(wd):
    sleep(1)

    room_list = wd.find_elements(By.XPATH,"/html/body/div[1]/div/div[2]/div/div/div[3]/ul/li")
    print(len(room_list))

    temp_list = []

    for room in room_list:
        temp = {}
        try:
            # temp["title"] = room.find_element(By.XPATH,"./a[2]/li[1]/a[2]").get_attribute("title")
            temp["url"] = room.find_element(By.XPATH,"./a[1]").get_attribute("href")
            temp["owner"] = room.find_element(By.XPATH,"./span[1]/span[1]/i").text
            temp["type"] = room.find_element(By.XPATH,"./span[1]/span[2]/i[2]").text
            # temp["num"] = room.find_element(By.XPATH,"./span[1]/span[3]/i[2]").text
            temp_list.append(temp)
        except:
            continue
        
    return temp_list


def save_data(temp_list):
    count = 1
    for temp in temp_list:
        print(count,temp)
        count += 1
def HuyaDanmu(address,ua):
    options = webdriver.ChromeOptions()            # 定义Chrome配置参数
    options.add_argument('--ignore-certificate-errors')           # 忽略https证书错误
    options.add_argument('user-agent=' + ua)                      # 设置user-agent,取消浏览器被识别出来
    # options.add_argument('--headless')                            # 该‘浏览器不提供可视化页面’设置去掉
    # options.add_argument('blink-settings=imagesEnabled=false')  # 添加不加载图片设置,提升速度

    s = Service(address)                                            # 加载Chrome服务
    wd = webdriver.Chrome(service=s, options=options)                 # 创建浏览器实例
    wd.implicitly_wait(160)                                          # 让浏览器实例隐式等待60秒,方便浏览器加载完成后就可以获取页面的元素
    # 调用WebDriver 对象的get方法 可以让浏览器打开指定网址
    wd.get('https://www.huya.com')
    #点击登陆出现扫码登陆
    # wd.find_element(By.LINK_TEXT, "登录").click()
    #账号密码在记事本中,第一行账号,第二行密码
    with open(r"G:\TDDOWNLOAD\qq自动化登录虎牙\LoginHuyaByQ\HY账号密码.txt", "r", encoding="utf-8") as g:
        hypassword = g.readlines()
        print(hypassword[0])
        print(hypassword[1])
    # wd.switch_to.frame("UDBSdkLgn_iframe")                          #定位第一个弹窗并关闭
    # wd.find_element(By.ID, 'close-udbLogin').click()

    action = ActionChains(wd)
    denglu = wd.find_element(By.CLASS_NAME, "LoginHd--1Jf6S0CCU3DUkJdjVqVn3")   #定位悬停位置
    action.move_to_element(denglu).perform()                                      #鼠标悬停

    # wd.find_element(By.LINK_TEXT, "点我注册").click()
    # wd.switch_to.frame("UDBSdkLgn_iframe")
    # wd.find_element(By.CLASS_NAME, 'returnlogin-btn').click()
    # # wd.find_element(By.XPATH, "//*[@id='account-login-form']/div[1]/input").send_keys(hypassword[0])
    # wd.find_element(By.XPATH, "//*[@id=‘account-login-form’]/div[1]/input").send_keys(hypassword[0])
    #
    # # wd.find_element(By.XPATH, "//*[@id='account-login-form']/div[2]/input").send_keys(hypassword[1])
    # wd.find_element(By.XPATH, "//*[@id=‘account-login-form’]/div[2]/input").send_keys(hypassword[1])
    # wd.find_element(By.XPATH, "//*[@id='login-btn']").click()
    sleep(10)



#打印模拟器板块主播数量以及具体信息
    wd.get("https://www.huya.com/g/3203#cate-1-4507-0")
    temp_list_monq = parse_data(wd)
    save_data(temp_list_monq)

    wd.get("https://www.huya.com/g/3203")
    temp_list = parse_data(wd)
    save_data(temp_list)

    while True:

        for roomherf in temp_list:
            wd.get(roomherf['url'])

            f = open("G:\TDDOWNLOAD\qq自动化登录虎牙\LoginHuyaByQ\主播打招呼文本.txt", "r", encoding="UTF-8")  # 设置文件对象
            lines = f.readlines()  # 将txt文件的所有内容读入到字符串str中
            f.close()

            messageBox = wd.find_element(By.XPATH, '//*[@id="pub_msg_input"]')  # 找到页面上的输入框,用于发送弹幕
            messageBut = wd.find_element(By.XPATH, '//*[@id="msg_send_bt"]')  # 找到发送弹幕按钮
            danmu = choice(lines).strip('\n')  # 随机从文件中读取一个弹幕
            messageBox.send_keys(danmu)  # 在输入框中输入弹幕
            sleep(1)
            messageBut.click()  # 点击发送弹幕
            sleep(20)
        break
            # try:
            #     el_next = wd.find_element_by_xpath("//a[@class='laypage_next']")
            #     wd.execute_script("scrollTo(0, 100000)")
            #     el_next.click()
            # except:
            #     print("结束!")
            # break





if __name__ == '__main__':
    # f = open("settings.txt", "r",encoding='utf-8')  # 设置文件对象
    # lines = f.readlines()  # 将txt文件的所有内容读入到字符串str中
    address="G:\TDDOWNLOAD\qq自动化登录虎牙\LoginHuyaByQ\chromedriver.exe"
    ua="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/109.0.0.0 Safari/537.36"
    # f.close()

    HuyaDanmu(address,ua)
    input("输入任意键结束")



现在这个网页怎么获取登录框信息,切换不到那个ifram框里,捣鼓半天没弄不好,想爬取每个网页信息 现在最多获取7个,还请各位大佬帮忙,谢谢了,代码让我改的烂摊子了

想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 昨天 16:35 | 显示全部楼层
要用 Selenium 自动登录虎牙账号并爬取房间信息,可以按照以下步骤进行修改和完善代码:

1. **安装相关库(如果未安装):**
pip install selenium

2. **初始化 WebDriver 和登录功能:**
from selenium import webdriver
   from selenium.webdriver.common.by import By
   from selenium.webdriver.chrome.service import Service
   from time import sleep

   def login_huya(wd, username, password):
       # 打开虎牙登录页
       wd.get("https://www.huya.com")

       # 点击登录按钮
       login_button = wd.find_element(By.LINK_TEXT, "登录")
       login_button.click()

       # 切换到账号登录方式
       wd.switch_to.frame(wd.find_element(By.ID, 'UDBSdkLgn_iframe_content'))
       account_login = wd.find_element(By.CSS_SELECTOR, ".udbsdk_udblogin_tab-item:nth-child(2)")
       account_login.click()

       # 输入用户名和密码
       wd.find_element(By.ID, "account-login-accountName").send_keys(username)
       wd.find_element(By.ID, "account-login-password").send_keys(password)

       # 点击登录
       wd.find_element(By.ID, "login-btn-submit").click()

       # 确保登录成功,可以添加合适的等待时间
       sleep(5)

   def parse_data(wd):
       sleep(1)
       room_list = wd.find_elements(By.XPATH, "/html/body/div/div/div/div/div/div/ul/li")
       temp_list = []

       for room in room_list:
           temp = {}
           try:
               temp['url'] = room.find_element(By.XPATH, "./a").get_attribute("href")
               temp['title'] = room.find_element(By.XPATH, "./a").get_attribute("title")
               temp['info'] = room.find_element(By.XPATH, "./span/span/i").text
               temp_list.append(temp)
           except Exception as e:
               print(e)
               continue

       return temp_list

   def save_data(temp_list):
       count = 1
       for temp in temp_list:
           print(count, temp)
           count += 1

   def HuyaDanmu(address, ua, username, password):
       options = webdriver.ChromeOptions()
       options.add_argument('--ignore-certificate-errors')
       options.add_argument('user-agent=' + ua)

       s = Service(address)
       wd = webdriver.Chrome(service=s, options=options)
       wd.implicitly_wait(60)

       login_huya(wd, username, password)

       temp_list = parse_data(wd)
       save_data(temp_list)
       wd.quit()

   # 示例调用
   HuyaDanmu("path_to_chromedriver", "your_user_agent", "your_username", "your_password")

   请将 `"path_to_chromedriver"` 修改为 `chromedriver` 的实际路径,将 `"your_user_agent"` 修改为实际的浏览器 UA(用户代理), `"your_username"` 和 `"your_password"` 修改为实际的虎牙账号和密码。

注意:由于虎牙的登录方式较为复杂,有时可能会遇到验证码或其他验证流程。以上脚本使用了账号密码登录方式,如果虎牙过程中有任何修改,脚本可能需要相应更新。另外,请确保访问控制策略和节操。

以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-9-25 21:20

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表