Files
NaverSearcher/NaverSearcher/Form1.cs
2021-08-05 10:03:57 +09:00

602 lines
23 KiB
C#

using Newtonsoft.Json.Linq;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.Support.UI;
using SeleniumExtras.WaitHelpers;
using System;
using System.Collections.ObjectModel;
using System.Linq;
using System.Threading;
using System.Windows.Forms;
using WebSocketSharp;
namespace NaverSearcher
{
public partial class Form1 : Form
{
private static Random m_Random = new Random();
WebSocket m_WebSocket = new WebSocket("ws://api.inrose.com");
Thread m_Thread = new Thread(NaverSearcherExcute);
public Form1()
{
InitializeComponent();
m_WebSocket.OnOpen += (sender, e) =>
{
m_WebSocket.Send("{\"GUID\":\"" + Properties.Settings.Default.GUID + "\"}");
};
m_WebSocket.OnMessage += (sender, e) =>
{
JObject _JObject = JObject.Parse(e.Data);
if (_JObject.ContainsKey("keepalive"))
{
}
if (_JObject.ContainsKey("key_pairs"))
{
if (m_Thread.ThreadState != ThreadState.Unstarted)
m_Thread.Join();
if (m_Thread.ThreadState == ThreadState.Stopped)
m_Thread = new Thread(NaverSearcherExcute);
m_Thread.Start(_JObject);
}
};
m_WebSocket.OnError += (sender, e) =>
{
System.Diagnostics.Trace.WriteLine(e.Message);
};
m_WebSocket.OnClose += (sender, e) =>
{
System.Diagnostics.Trace.WriteLine(e.Reason);
if (m_Thread.ThreadState != ThreadState.Unstarted)
m_Thread.Join();
Thread.Sleep(2000);
m_WebSocket.Connect();
};
#if DEBUG
// To change the logging level.
m_WebSocket.Log.Level = WebSocketSharp.LogLevel.Trace;
// To change the wait time for the response to the Ping or Close.
//ws.WaitTime = TimeSpan.FromSeconds (10);
// To emit a WebSocket.OnMessage event when receives a ping.
//ws.EmitOnPing = true;
#endif
// To enable the Per-message Compression extension.
//ws.Compression = CompressionMethod.Deflate;
// To validate the server certificate.
/*
ws.SslConfiguration.ServerCertificateValidationCallback =
(sender, certificate, chain, sslPolicyErrors) => {
ws.Log.Debug (
String.Format (
"Certificate:\n- Issuer: {0}\n- Subject: {1}",
certificate.Issuer,
certificate.Subject
)
);
return true; // If the server certificate is valid.
};
*/
// To send the credentials for the HTTP Authentication (Basic/Digest).
//ws.SetCredentials ("nobita", "password", false);
// To send the Origin header.
//ws.Origin = "http://localhost:4649";
// To send the cookies.
//ws.SetCookie (new Cookie ("name", "nobita"));
//ws.SetCookie (new Cookie ("roles", "\"idiot, gunfighter\""));
// To connect through the HTTP Proxy server.
//ws.SetProxy ("http://localhost:3128", "nobita", "password");
// To enable the redirection.
//ws.EnableRedirection = true;
// Connect to the server.
m_WebSocket.Connect();
// Connect to the server asynchronously.
//m_WebSocket.ConnectAsync();
// 하루에 두번 검색
// {{바나나우유 라떼, 초코우유 라떼}, {민트초코바, 민트색}}
// 검색어 1페어
// 검색어 입력 (검색어 1)
// 검색어 확인
// 스크롤 내린다.
// 20 ~ 60초 대기
// 아무 게시글 클릭
// 이동된 페이지 작업
// 스크롤 내리기
// 20 ~ 60초 대기
// 새창 닫기
// 검색어 입력 (검색어 2, 기존 대기창)
// 검색어 확인
// 스크롤 내린다.
// 20 ~ 60초 대기
// 아무 게시글 클릭
// 이동된 페이지 작업
// 스크롤 내리기
// 20 ~ 60초 대기
// 새창 닫기
// 아무거나 검색 (비선형 검색어)
// 검색어 확인
// 스크롤 내린다.
// 20 ~ 60초 대기
// 아무 게시글 클릭
// 이동된 페이지 작업
// 스크롤 내리기
// 20 ~ 60초 대기
// 새창 닫기
// 검색어 2페어
// 로그인 여부 확인
// 로그아웃 실행
// 네이버 메인
// 스크롤 내린다.
// 20 ~ 60초 대기
// 검색어 입력 (검색어 1)
// 검색어 확인
// 스크롤 내린다.
// 20 ~ 60초 대기
// 아무 게시글 클릭
// 이동된 페이지 작업
// 스크롤 내리기
// 20 ~ 60초 대기
// 전부 닫기
// 로그인 여부 확인
// 로그아웃 실행
// 네이버 메인
// 스크롤 내린다.
// 20 ~ 60초 대기
// 검색어 입력 (검색어 2, 기존 대기창)
// 검색어 확인
// 스크롤 내린다.
// 20 ~ 60초 대기
// 아무 게시글 클릭
// 이동된 페이지 작업
// 스크롤 내리기
// 20 ~ 60초 대기
// 새창 닫기
// 아무거나 검색 (비선형 검색어)
// 검색어 확인
// 스크롤 내린다.
// 20 ~ 60초 대기
// 아무 게시글 클릭
// 이동된 페이지 작업
// 스크롤 내리기
// 20 ~ 60초 대기
// 새창 닫기
}
private static void NaverSearcherExcute(Object _Object)
{
JObject _JObject = (JObject)_Object;
ChromeOptions _ChromeOptions = new ChromeOptions();
_ChromeOptions.AddArguments("disable-infobars");
_ChromeOptions.AddArguments("--js-flags=--expose-gc");
_ChromeOptions.AddArguments("--enable-precise-memory-info");
_ChromeOptions.AddArguments("--disable-popup-blocking");
_ChromeOptions.AddArguments("--disable-default-apps");
_ChromeOptions.AddArguments("--headless");
_ChromeOptions.AddArguments("user - agent = Mozilla / 5.0(Macintosh; Intel Mac OS X 10_12_6) AppleWebKit / 537.36(KHTML, like Gecko) Chrome / 61.0.3163.100 Safari / 537.36");
// 프록시 설정
//Proxy proxy = new Proxy();
//proxy.Kind = ProxyKind.Manual;
//proxy.IsAutoDetect = false;
//proxy.HttpProxy =
//proxy.SslProxy = ip;
//_ChromeOptions.Proxy = proxy;
//_ChromeOptions.AddArgument("ignore-certificate-errors");
ChromeDriverService _ChromeDriverService = ChromeDriverService.CreateDefaultService();
_ChromeDriverService.HideCommandPromptWindow = true;
//_ChromeDriver = new ChromeDriver(_ChromeDriverService, _ChromeOptions);
ChromeDriver _ChromeDriver = new ChromeDriver();
//_ChromeOptions.add_argument("user-agent=Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko")
WebDriverWait _WebDriverWait = new WebDriverWait(_ChromeDriver, TimeSpan.FromSeconds(3));
try
{
foreach (var key_words in _JObject["key_pairs"])
{
// 로그인 여부 확인
// 로그아웃 실행
// 네이버 메인
// 스크롤 내린다.
// 20 ~ 60초 대기
try
{
_ChromeDriver.Navigate().GoToUrl(@"https://naver.com");
_WebDriverWait.Until(ExpectedConditions.ElementIsVisible(By.XPath("//*[@id=\"query\"]")));
string _logout = @"/html/body/div/div/div[1]/div[1]/a[1]";
if (IsElementPresent(_ChromeDriver, By.XPath(_logout)))
{
_ChromeDriver.FindElement(By.XPath(_logout)).Click();
}
foreach (var key_word in key_words["key_words"])
{
// 검색어 입력 (검색어 1)
// 검색어 확인
// 스크롤 내린다.
// 20 ~ 60초 대기
// 아무 게시글 클릭
// 이동된 페이지 작업
// 스크롤 내리기
// 20 ~ 60초 대기
// 새창 닫기
try
{
_ChromeDriver.Navigate().GoToUrl(@"https://naver.com");
string _query_xpath = "//*[@id=\"query\"]";
_WebDriverWait.Until(ExpectedConditions.ElementIsVisible(By.XPath(_query_xpath)));
IWebElement _query_elment = _ChromeDriver.FindElement(By.XPath(_query_xpath));
foreach (var item in StringParser.CharacterMakeHistory(key_word["key_word"].ToString()))
{
_query_elment.Clear();
_query_elment.SendKeys(item);
Thread.Sleep(m_Random.Next(500, 1000));
}
_query_elment.SendKeys(OpenQA.Selenium.Keys.Enter);
((IJavaScriptExecutor)_ChromeDriver).ExecuteScript("window.scrollBy(0, document.body.scrollHeight);");
Thread.Sleep(m_Random.Next(2000, 6000));
ReadOnlyCollection<IWebElement> links = _ChromeDriver.FindElements(By.CssSelector("a[href*='https://']"));
int _try = links.Count;
do
{
try
{
int _sel = m_Random.Next(0, links.Count);
string kknd = links[_sel].GetAttribute("href");
links[_sel].Click();
break;
}
catch (Exception ex)
{
Console.WriteLine("=== 무작위 링크 접속 ===");
Console.WriteLine(ex.Message);
}
} while (--_try > 0);
((IJavaScriptExecutor)_ChromeDriver).ExecuteScript("window.scrollBy(0, document.body.scrollHeight);");
Thread.Sleep(m_Random.Next(2000, 6000));
if (_ChromeDriver.WindowHandles.First() != _ChromeDriver.WindowHandles.Last())
{
_ChromeDriver.SwitchTo().Window(_ChromeDriver.WindowHandles.Last());
_ChromeDriver.Close();
_ChromeDriver.SwitchTo().Window(_ChromeDriver.WindowHandles.First());
}
}
catch (Exception ex)
{
Console.WriteLine("=== 검색어 ===");
Console.WriteLine(ex.Message);
}
}
}
catch (Exception ex)
{
Console.WriteLine("=== 검색어 페어 ===");
Console.WriteLine(ex.Message);
}
}
// 결과 던지기
using (WebSocket _WebSocket = new WebSocket("ws://api.inrose.com"))
{
_WebSocket.OnOpen += (sender, e) => {
_WebSocket.Send("{\"GUID\":\"" + Properties.Settings.Default.GUID + "\", \"keyword\":" + _JObject + ", \"done\":true}");
};
_WebSocket.OnMessage += (sender, e) => {
};
_WebSocket.OnError += (sender, e) => {
};
_WebSocket.OnClose += (sender, e) => {
};
_WebSocket.Connect();
Thread.Sleep(5000);
}
}
catch (Exception ex)
{
Console.WriteLine("=== 실행 ===");
Console.WriteLine(ex.Message);
}
finally
{
_ChromeDriver.Quit();
}
}
private void Excute(JObject _JObject)
{
try
{
ChromeDriver _ChromeDriver = new ChromeDriver();
WebDriverWait _WebDriverWait = new WebDriverWait(_ChromeDriver, TimeSpan.FromSeconds(3));
foreach (var key_words in _JObject["key_pairs"])
{
// 로그인 여부 확인
// 로그아웃 실행
// 네이버 메인
// 스크롤 내린다.
// 20 ~ 60초 대기
try
{
_ChromeDriver.Navigate().GoToUrl(@"https://naver.com");
_WebDriverWait.Until(ExpectedConditions.ElementIsVisible(By.XPath("//*[@id=\"query\"]")));
string _logout = @"/html/body/div/div/div[1]/div[1]/a[1]";
if (IsElementPresent(_ChromeDriver, By.XPath(_logout)))
{
_ChromeDriver.FindElement(By.XPath(_logout)).Click();
}
foreach (var key_word in key_words["key_words"])
{
// 검색어 입력 (검색어 1)
// 검색어 확인
// 스크롤 내린다.
// 20 ~ 60초 대기
// 아무 게시글 클릭
// 이동된 페이지 작업
// 스크롤 내리기
// 20 ~ 60초 대기
// 새창 닫기
try
{
_ChromeDriver.Navigate().GoToUrl(@"https://naver.com");
string _query_xpath = "//*[@id=\"query\"]";
_WebDriverWait.Until(ExpectedConditions.ElementIsVisible(By.XPath(_query_xpath)));
IWebElement _query_elment = _ChromeDriver.FindElement(By.XPath(_query_xpath));
foreach (var item in StringParser.CharacterMakeHistory(key_word["key_word"].ToString()))
{
_query_elment.Clear();
_query_elment.SendKeys(item);
Thread.Sleep(m_Random.Next(500, 1000));
}
_query_elment.SendKeys(OpenQA.Selenium.Keys.Enter);
((IJavaScriptExecutor)_ChromeDriver).ExecuteScript("window.scrollBy(0, document.body.scrollHeight);");
Thread.Sleep(m_Random.Next(2000, 6000));
ReadOnlyCollection<IWebElement> links = _ChromeDriver.FindElements(By.CssSelector("a[href*='https://']"));
int _try = links.Count;
do
{
try
{
int _sel = m_Random.Next(0, links.Count);
string kknd = links[_sel].GetAttribute("href");
links[_sel].Click();
break;
}
catch (Exception ex)
{
Console.WriteLine("=== 무작위 링크 접속 ===");
Console.WriteLine(ex.Message);
}
} while (--_try > 0);
((IJavaScriptExecutor)_ChromeDriver).ExecuteScript("window.scrollBy(0, document.body.scrollHeight);");
Thread.Sleep(m_Random.Next(2000, 6000));
if (_ChromeDriver.WindowHandles.First() != _ChromeDriver.WindowHandles.Last())
{
_ChromeDriver.SwitchTo().Window(_ChromeDriver.WindowHandles.Last());
_ChromeDriver.Close();
_ChromeDriver.SwitchTo().Window(_ChromeDriver.WindowHandles.First());
}
}
catch (Exception ex)
{
Console.WriteLine("=== 검색어 ===");
Console.WriteLine(ex.Message);
}
}
}
catch (Exception ex)
{
Console.WriteLine("=== 검색어 페어 ===");
Console.WriteLine(ex.Message);
}
}
/*
var elem = _ChromeDriver.FindElementByXPath("//*");
var source_code = elem.GetAttribute("outerHTML");
((IJavaScriptExecutor)_ChromeDriver).ExecuteScript("window.open();");
_ChromeDriver.SwitchTo().Window(_ChromeDriver.WindowHandles[1]);
string winHandleBefore = _ChromeDriver.CurrentWindowHandle;
//_ChromeDriver.SwitchTo().Window(winHandleBefore);
_WebDriverWait = new WebDriverWait(_ChromeDriver, TimeSpan.FromSeconds(3));
elem = _ChromeDriver.FindElementByXPath("//*");
source_code = elem.GetAttribute("outerHTML");
_ChromeDriver.SwitchTo().Window(_ChromeDriver.WindowHandles[1]);
winHandleBefore = _ChromeDriver.CurrentWindowHandle;
_WebDriverWait = new WebDriverWait(_ChromeDriver, TimeSpan.FromSeconds(3));
elem = _ChromeDriver.FindElementByXPath("//*");
source_code = elem.GetAttribute("outerHTML");
_ChromeDriver.Navigate().GoToUrl(@"https://inrose.com");
_WebDriverWait = new WebDriverWait(_ChromeDriver, TimeSpan.FromSeconds(3));
elem = _ChromeDriver.FindElementByXPath("//*");
source_code = elem.GetAttribute("outerHTML");
_ChromeDriver.SwitchTo().Window(_ChromeDriver.WindowHandles.First());
winHandleBefore = _ChromeDriver.CurrentWindowHandle;
_WebDriverWait = new WebDriverWait(_ChromeDriver, TimeSpan.FromSeconds(3));
elem = _ChromeDriver.FindElementByXPath("//*");
source_code = elem.GetAttribute("outerHTML");
_ChromeDriver.Navigate().GoToUrl(@"https://google.com");
_WebDriverWait = new WebDriverWait(_ChromeDriver, TimeSpan.FromSeconds(3));
elem = _ChromeDriver.FindElementByXPath("//*");
source_code = elem.GetAttribute("outerHTML");
return;
_ChromeDriver.Navigate().GoToUrl(@"https://www.instagram.com/");
_WebDriverWait = new WebDriverWait(_ChromeDriver, TimeSpan.FromSeconds(3));
//_WebDriverWait.IgnoreExceptionTypes(typeof(NoSuchElementException));
string _id_xpath = "//*[@id=\"loginForm\"]/div/div[1]/div/label/input";
string _pass_xpath = "//*[@id=\"loginForm\"]/div/div[2]/div/label/input";
string _login_xpath = "//*[@id=\"loginForm\"]/div/div[3]/button/div";
_WebDriverWait.Until(ExpectedConditions.ElementIsVisible(By.XPath(_login_xpath)));
_ChromeDriver.FindElement(By.XPath(_id_xpath)).SendKeys(@"leeumdkj@gmail.com");
_ChromeDriver.FindElement(By.XPath(_pass_xpath)).SendKeys(@"awdr1536!!");
_ChromeDriver.FindElement(By.XPath(_login_xpath)).Click();
// 알림 존재시
string _alert_xpath = "//*[@id=\"react-root\"]/section/main/div/div/div/div/button";
_WebDriverWait.Until(ExpectedConditions.ElementIsVisible(By.XPath(_alert_xpath)));
try
{
_ChromeDriver.FindElement(By.XPath(_alert_xpath)).Click();
}
catch (Exception)
{
}
_alert_xpath = "/html/body/div[4]/div/div/div/div[3]/button[2]";
_WebDriverWait.Until(ExpectedConditions.ElementIsVisible(By.XPath(_alert_xpath)));
try
{
_ChromeDriver.FindElement(By.XPath(_alert_xpath)).Click();
}
catch (Exception)
{
}
//_search_xpath = "//*[@id=\"react-root\"]/section/nav/div[2]/div/div/div[2]/input";
//_WebDriverWait.Until(ExpectedConditions.ElementIsVisible(By.XPath(_search_xpath)));
//_ChromeDriver.FindElement(By.XPath(_search_xpath)).SendKeys(@"인플 검색");
*/
}
catch (Exception ex)
{
Console.WriteLine("=== 실행 ===");
Console.WriteLine(ex.Message);
}
}
private void button1_Click(object sender, EventArgs e)
{
if (m_WebSocket.ReadyState == WebSocketState.Closed)
m_WebSocket.Connect();
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
if (m_Thread.ThreadState != ThreadState.Unstarted)
m_Thread.Join();
}
private static bool IsElementPresent(IWebDriver _IWebDriver, By by)
{
try
{
_IWebDriver.FindElement(by);
return true;
}
catch (NoSuchElementException)
{
return false;
}
}
}
}