Слияние кода завершено, страница обновится автоматически
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.Interactions;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace ClassRpa
{
/// <summary>
/// MainWindow.xaml 的交互逻辑
/// </summary>
public partial class MainWindow : Window
{
static Model.ClassInfo classInfo = null;
static List<Model.ClassInfo> classInfos = new List<Model.ClassInfo>();
static IWebDriver webDriver;
static IWebElement webElement;
static List<IWebElement> webElements;
static bool isSpidering = false;
static Thread spider = new Thread(spiderIng);
/// <summary>
/// 视频播放进度
/// </summary>
static ObservableCollection<Model.ClassPlayInfo> classPlayInfos { get; set; } = new ObservableCollection<Model.ClassPlayInfo>();
public MainWindow()
{
InitializeComponent();
ChromeDriverService driverService = ChromeDriverService.CreateDefaultService();
driverService.HideCommandPromptWindow = true;//关闭黑色cmd窗口
ChromeOptions options = new ChromeOptions();
// 不显示浏览器
// options.AddArgument("--headless");
// GPU加速可能会导致Chrome出现黑屏及CPU占用率过高,所以禁用
// options.AddArgument("--disable-gpu");
// 伪装user-agent
// options.AddArgument("user-agent=Mozilla/5.0 (iPhone; CPU iPhone OS 10_3 like Mac OS X) AppleWebKit/602.1.50 (KHTML, like Gecko) CriOS/56.0.2924.75 Mobile/14E5239e Safari/602.1");
// 设置chrome启动时size大小
//options.AddArgument("--window-size=414,736");
// 禁用图片
//options.AddUserProfilePreference("profile.default_content_setting_values.images", 2);
webDriver = new ChromeDriver(driverService, options);
//如果查找元素在5S内还没有找到
webDriver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(5));
string url = "https://mingshi8.hbte.com.cn/index.php/home/login/login.html";
webDriver.Navigate().GoToUrl(url);
//执行JS(将滚动条拉到底部):
//((IJavaScriptExecutor)webDriver).ExecuteScript("window.scrollTo(0, document.body.scrollHeight)");
// 获取标签(以多Class为例):
// ReadOnlyCollection<IWebElement> elements = driver.FindElements(By.CssSelector("[class='item goWork']"));
// Log("输入帐号");
webDriver.Manage().Window.Maximize();
webDriver.FindElement(By.Name("id_number")).SendKeys("130525197902067614");
// Log("输入密码");
webDriver.FindElement(By.Name("pwd")).SendKeys("067614");
webDriver.FindElement(By.Name("code")).Click();
//classInfos.Add(new Model.ClassInfo { CourseName="123", CourseTheme="234", CourseVideo="345", Hour="3.0", State="已学完", Url="www.baidu.com" });
//dg.ItemsSource= classInfos;
items.ItemsSource = classPlayInfos;
}
private void btLogin_Click(object sender, RoutedEventArgs e)
{
webDriver.FindElement(By.Name("code")).SendKeys(tbCode.Text);
webDriver.FindElement(By.Id("zone_login")).Click();
#region 进入个人中心-加载用户信息
webDriver.Url = "https://mingshi8.hbte.com.cn/index.php/home/index/index.html";
webDriver.Navigate();
webElement = webDriver.FindElement(By.ClassName("zjs_gr"));
webElements = webElement.FindElements(By.TagName("li")).ToList();
tb1.Text = webElements[0].Text;
tb2.Text = webElements[1].Text;
tb3.Text = webElements[2].Text;
tb4.Text = webElements[3].Text;
tb5.Text = webElements[4].Text;
tb6.Text = webElements[5].Text;
#endregion
#region 进入进行中的项目
webDriver.Url = "https://mingshi8.hbte.com.cn/index.php/home/project/index.html";
webDriver.Navigate();
webDriver.FindElements(By.ClassName("jinxingProduct_2"))[1].Click();
webDriver.FindElement(By.Id("tiao")).Click();
webElement = webDriver.FindElement(By.Id("tbody4"));
webElement.FindElements(By.TagName("td")).SingleOrDefault(a => a.Text.Contains("C4")).Click();//弹出课程层
webElement = webDriver.FindElement(By.Id("soniframe"));
webDriver.SwitchTo().Frame(webElement);
webElement = webDriver.FindElement(By.Id("courseList"));
webElements = webElement.FindElements(By.TagName("tr")).ToList();
for (int i = 0; i < webElements.Count - 1; i++)
{
classInfos.Add(new Model.ClassInfo
{
CourseTheme = webElements[i].FindElements(By.TagName("td"))[0].Text,
CourseName = webElements[i].FindElements(By.TagName("td"))[1].Text,
CourseVideo = webElements[i].FindElements(By.TagName("td"))[2].Text,
Hour = webElements[i].FindElements(By.TagName("td"))[3].Text,
State = "",// webElements[i].FindElements(By.TagName("td"))[4].Text,
Url = webElements[i].FindElement(By.TagName("a")).GetAttribute("onclick").Replace("javascript:IsLogin('", "https://hbt.gpa.enetedu.com").Replace("');", "")
});
}
dg.ItemsSource = classInfos;
#endregion
}
private void BtAuto_Click(object sender, RoutedEventArgs e)
{
spider.IsBackground = true;
spider.Start();
}
private static void spiderIng()
{
while (true)
{
if (isSpidering == false)
{
classInfo = classInfos.FirstOrDefault(a => a.State == "");
if (classInfo != null)
{
webDriver.Url = classInfo.Url;
webDriver.Navigate();
Thread.Sleep(1000 * 3);//等待3秒
var project_id = webDriver.FindElement(By.Id("project_id")).GetAttribute("value");
var course_id = webDriver.FindElement(By.Id("courseID")).GetAttribute("value");
var classtopic_id = webDriver.FindElement(By.Id("classtopic_id")).GetAttribute("value");
var coursewareid = "";
webElements = webDriver.FindElements(By.ClassName("courseName_div")).ToList();
for (int j = 0; j < webElements.Count; j++)
{
if (webElements[j].Text.Contains("课程章节"))
{
#region 打开视频网页
webElements[j].FindElements(By.TagName("li")).ToList().ForEach(a =>
{
coursewareid = a.FindElement(By.TagName("a")).GetAttribute("onclick").Replace("courseplay(", "").Replace(")", "");
string SplitName = a.FindElement(By.TagName("a")).Text;//小章节课程名称
if (!a.FindElement(By.TagName("span")).Text.Equals("已学完1"))
{
((IJavaScriptExecutor)webDriver).ExecuteScript("window.open('" + "https://hbt.gpa.enetedu.com//MyCourse/MyCurriculum?ProcesFlag=true&courseID=" +
course_id + "&project_id=" + project_id + "&coursewareid=" + coursewareid + "&classtopic_id=" + classtopic_id + "','_blank');");
ThreadPool.QueueUserWorkItem(delegate
{
System.Threading.SynchronizationContext.SetSynchronizationContext(new
System.Windows.Threading.DispatcherSynchronizationContext(System.Windows.Application.Current.Dispatcher));
System.Threading.SynchronizationContext.Current.Post(p1 =>
{
classPlayInfos.Add(new Model.ClassPlayInfo
{
ClassName = SplitName,
CurWidth = 0,
Finished = false,
FullWidth = 0,
Index = coursewareid,
Process = "0.00"
});
}, null);
});
}
else
{
ThreadPool.QueueUserWorkItem(delegate
{
System.Threading.SynchronizationContext.SetSynchronizationContext(new
System.Windows.Threading.DispatcherSynchronizationContext(System.Windows.Application.Current.Dispatcher));
System.Threading.SynchronizationContext.Current.Post(p1 =>
{
classPlayInfos.Add(new Model.ClassPlayInfo
{
ClassName = SplitName,
CurWidth = 100,
Finished = true,
FullWidth = 100,
Index = coursewareid,
Process = "100.00%"
});
}, null);
});
}
});
#endregion
}
else if (webElements[j].Text.Contains("文本章节"))
{
}
}
if (webDriver.WindowHandles.Count > 1)
{
webDriver.Close();
}
classInfo.State = "进行中";
isSpidering = true;
}
else
{
MessageBox.Show("刷课完成,进行下一个课程");
}
}
else
{
//进行刷卡状态判断
for (int i = 0; i < webDriver.WindowHandles.Count(); i++)
{
webDriver = webDriver.SwitchTo().Window(webDriver.WindowHandles[i]);//切换窗口判断进度或者是否播放
string coursewareid = webDriver.FindElement(By.Id("coursewareid")).GetAttribute("value");//获取课程id
webElement = webDriver.FindElement(By.ClassName("videoCourse")).FindElement(By.TagName("iframe"));//获取Iframe中的播放器对象
decimal fullWidth = Convert.ToDecimal(webElement.GetCssValue("width").Replace("px", ""));//进度条总长度
webDriver.SwitchTo().Frame(webElement);
decimal curWidth = Convert.ToDecimal(webDriver.FindElement(By.ClassName("qplayer-barcurr")).GetCssValue("width").Replace("px", "")); //当前进度条长度
try
{
var classinfo = classPlayInfos.SingleOrDefault(a => a.Index.Equals(coursewareid));
if (classinfo != null)
{
if (curWidth != fullWidth && classinfo.CurWidth == curWidth)
{
//播放button
//qplayer-center-btn
Actions act = new Actions(webDriver);
webElement = webDriver.FindElement(By.ClassName("qplayer-center-btn"));
act.MoveToElement(webElement);
act.Perform();
Thread.Sleep(500);
webElement.Click();//播放
}
ThreadPool.QueueUserWorkItem(delegate
{
System.Threading.SynchronizationContext.SetSynchronizationContext(new
System.Windows.Threading.DispatcherSynchronizationContext(System.Windows.Application.Current.Dispatcher));
System.Threading.SynchronizationContext.Current.Post(p1 =>
{
classinfo.FullWidth = fullWidth;
classinfo.CurWidth = curWidth;
classinfo.Process = (classinfo.CurWidth*100 / classinfo.FullWidth).ToString("0.00") ;
if (fullWidth == curWidth)
{
classinfo.Finished = true;
}
}, null);
});
//如果视频播放完成,并且Tab不止一个时关闭当前
if (classinfo.Finished)
{
//视频播放完毕
if (webDriver.WindowHandles.Count > 1)
{
webDriver.Close();
}
}
}
}
catch (Exception ex)
{
}
//如果所有的视频都播放完毕了!
if (classPlayInfos.All(a => a.Finished))
{
ThreadPool.QueueUserWorkItem(delegate
{
System.Threading.SynchronizationContext.SetSynchronizationContext(new
System.Windows.Threading.DispatcherSynchronizationContext(System.Windows.Application.Current.Dispatcher));
System.Threading.SynchronizationContext.Current.Post(p1 =>
{
//清空播放列表
while (classPlayInfos.Count > 0)
{
classPlayInfos.RemoveAt(0);
}
}, null);
});
isSpidering = false;
webDriver = webDriver.SwitchTo().Window(webDriver.WindowHandles[0]);
classInfo.State = "已学完";
break;
}
}
}
Thread.Sleep(1000);//休息5秒钟
}
}
}
}
Вы можете оставить комментарий после Вход в систему
Неприемлемый контент может быть отображен здесь и не будет показан на странице. Вы можете проверить и изменить его с помощью соответствующей функции редактирования.
Если вы подтверждаете, что содержание не содержит непристойной лексики/перенаправления на рекламу/насилия/вульгарной порнографии/нарушений/пиратства/ложного/незначительного или незаконного контента, связанного с национальными законами и предписаниями, вы можете нажать «Отправить» для подачи апелляции, и мы обработаем ее как можно скорее.
Опубликовать ( 0 )