本文整理汇总了C#中OpenQA.Selenium.Chrome.ChromeDriver.FindElementById方法的典型用法代码示例。如果您正苦于以下问题:C# ChromeDriver.FindElementById方法的具体用法?C# ChromeDriver.FindElementById怎么用?C# ChromeDriver.FindElementById使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类OpenQA.Selenium.Chrome.ChromeDriver
的用法示例。
在下文中一共展示了ChromeDriver.FindElementById方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: StartSession
public void StartSession()
{
//Run selenium
ChromeDriver cd = new ChromeDriver(Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "lib"));
cd.Url = @"https://login.yahoo.com/config/login?.src=fpctx&.intl=uk&.lang=en-GB&.done=https://uk.yahoo.com/%3fp=us";
cd.Navigate();
IWebElement e = cd.FindElementById("login-username");
e.SendKeys("");
e = cd.FindElementById("login-passwd");
e.SendKeys("");
e = cd.FindElementById("login-signin");
e.Click();
CookieContainer cc = new CookieContainer();
//Get the cookies
foreach (Cookie c in cd.Manage().Cookies.AllCookies)
{
string name = c.Name;
string value = c.Value;
cc.Add(new System.Net.Cookie(name, value, c.Path, c.Domain));
}
//cd.Quit();
//Fire off the request
HttpWebRequest hwr = (HttpWebRequest)HttpWebRequest.Create("https://uk.finance.yahoo.com/portfolio/pf_15/view/dv");
hwr.CookieContainer = cc;
hwr.Method = "POST";
hwr.ContentType = "application/x-www-form-urlencoded";
StreamWriter swr = new StreamWriter(hwr.GetRequestStream());
swr.Write("feeds=35");
swr.Close();
WebResponse wr = hwr.GetResponse();
string s = new StreamReader(wr.GetResponseStream()).ReadToEnd();
}
示例2: TestNewOrder_01
public void TestNewOrder_01()
{
using (var server = new ProjectSIAServer())
{
using (var chrome = new ChromeDriver())
{
chrome.Navigate().GoToUrl("http://localhost/local/add-order");
var memberName = chrome.FindElementById("input-memberName");
memberName.SendKeys("경원");
Thread.Sleep(1500);
chrome.Keyboard.SendKeys(Keys.Enter);
Thread.Sleep(500);
var productSearch = chrome.FindElementById("input-productInfo");
productSearch.Clear();
productSearch.SendKeys("머그 세");
Thread.Sleep(1000);
chrome.Keyboard.SendKeys(Keys.Enter);
Thread.Sleep(500);
chrome.Keyboard.SendKeys(Keys.ArrowUp);
Thread.Sleep(500);
productSearch.Clear();
productSearch.SendKeys("가방 꽃");
Thread.Sleep(1000);
chrome.Keyboard.SendKeys(Keys.ArrowDown);
chrome.Keyboard.SendKeys(Keys.Enter);
var buttonNewOrder = chrome.FindElementById("button-newOrder");
buttonNewOrder.Click();
Thread.Sleep(3000);
}
}
}
示例3: Scrape
private IEnumerable<Domain.Product> Scrape(string postcode)
{
var output = new List<Domain.Product>();
using (var driver = new ChromeDriver())
{
driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(30));
driver.Navigate().GoToUrl("http://www.dominos.co.uk");
driver.FindElementById("txtPostcode").SendKeys(postcode);
driver.FindElementById("btnStoreSearch").Click();
Thread.Sleep(1000);
driver.FindElementByCssSelector(".btn-secondary").Click();
Thread.Sleep(1000);
driver.Navigate().GoToUrl("https://www.dominos.co.uk/ProductCatalog/GetStoreContext");
string storeContextJson = driver.FindElementByTagName("pre").Text;
var storeContext = JsonConvert.DeserializeObject<StoreContext>(storeContextJson);
driver.Navigate().GoToUrl(
$"https://www.dominos.co.uk/ProductCatalog/GetStoreCatalog?collectionOnly={storeContext.SessionContext.CollectionOnly}&menuVersion={storeContext.SessionContext.MenuVersion}&storeId={storeContext.SessionContext.StoreId}");
string storeCatalogJson = driver.FindElementByTagName("pre").Text;
var products = JsonConvert.DeserializeObject<List<DTOs.Category>>(storeCatalogJson);
output = products
.SelectMany(p => p.Subcategories)
.SelectMany(p => p.Products)
.Where(p => !p.IsAlcohol)
.Where(p => p.Type != "PizzaLegend")
.Where(p => p.Name != "Half & Half")
.Where(p => p.Name != "Create Your Own")
.Select(p => new Domain.Product()
{
Id = p.Id.ToString(),
Name = p.Name,
Description = p.Description,
ImageUrl = p.ImageUrl.Replace("256x256", "1024x1024"),
GlutenFree = p.IsGlutenFree,
Hot = p.IsHot,
Vegetarian = p.IsVegetarian,
Price = p.DisplayPrice,
Category = (ProductCategory)Enum.Parse(typeof(ProductCategory), p.Type)
})
.ToList();
}
return output;
}
示例4: login
private ChromeDriver login(ChromeDriver cd, string uname, string pword)
{
cd.Url = "https://account.sonyentertainmentnetwork.com/login.action";
cd.Navigate();
IWebElement e = cd.FindElementById("signInInput_SignInID");
e.SendKeys(uname);
e = cd.FindElementById("signInInput_Password");
e.SendKeys(pword);
e = cd.FindElementById("signInButton");
e.Click();
return cd;
}
示例5: Index
public ActionResult Index()
{
var driver = new ChromeDriver();
//driver.Navigate().GoToUrl("http://diesel.elcat.kg");
driver.Navigate().GoToUrl("http://diesel.elcat.kg/index.php?act=Login");
// Get the page elements
var userNameField = driver.FindElementByName("UserName");
var userPasswordField = driver.FindElementByName("PassWord");
var loginButton = driver.FindElementByXPath("//input[@name='submit']");
// Type user name and password
userNameField.SendKeys("bishkek312");
userPasswordField.SendKeys("8061");
// and click the login button
loginButton.Click();
driver.Navigate().GoToUrl("http://diesel.elcat.kg/index.php?showtopic=43884872");
DeleteLastUp(driver);
var messageField = driver.FindElementById("fast-reply_textarea");
messageField.SendKeys(upMessageValue);
var sendButton = driver.FindElementByXPath("//input[@value='Отправить']");
return new EmptyResult();
//return View();
}
示例6: Main
static void Main(string[] args)
{
var url = "https://qa-antigo.elefanteletrado.com.br/Account/Login";
var driver = new ChromeDriver();
driver.Manage().Window.Maximize();
driver.Navigate().GoToUrl(url);
Thread.Sleep(2000);
var campoLogin = driver.FindElementById("name");
campoLogin.SendKeys("asdf");
Thread.Sleep(2000);
var botaoEntrar = driver.FindElementByCssSelector("input[type=submit][title='" + "Entrar" + "']");
botaoEntrar.Click();
Thread.Sleep(2000);
var mensagemInvalida = "Usuário não encontrado.";
var tagErro = driver.FindElementByClassName("error");
if (tagErro.Text != mensagemInvalida)
{
Console.WriteLine("Mensagem errada, veio: " + tagErro.Text + ", esperado: " + mensagemInvalida);
}
else
{
Console.WriteLine("Validação correta!");
}
}
示例7: ButtonHandler
public ButtonHandler(string id)
{
using (var driver = new ChromeDriver())
{
item = driver.FindElementById(id);
}
}
示例8: Manipulate
public void Manipulate()
{
ChromeDriver driver = new ChromeDriver();
HelpFunctions H = new HelpFunctions();
H.Navigate("http://us14.chatzy.com/37785015405504", driver);
H.Navigate("http://us14.chatzy.com", driver);
driver.Manage().Timeouts().ImplicitlyWait(new TimeSpan(0, 0, 100));
WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(5));
IWebElement element = null;
//= wait.Until(ExpectedConditions.ElementIsVisible(By.ClassName("X967")));
H.Button("//*[@id='X313']", driver);//Login/SignUp
driver.Manage().Timeouts().ImplicitlyWait(new TimeSpan(0, 0, 30));
element = wait.Until(ExpectedConditions.ElementIsVisible(By.XPath("//*[@id='X603']")));
H.InputInfo("//*[@id='X603']", "[email protected]", driver);//add email
driver.Manage().Timeouts().ImplicitlyWait(new TimeSpan(0, 0, 30));
H.Button("//*[@id='X6001']", driver); // choose the "I am regitered user"
driver.Manage().Timeouts().ImplicitlyWait(new TimeSpan(0, 0, 30));
H.InputInfo("//*[@id='X604']", "Amber001", driver); //Enter in the password
driver.Manage().Timeouts().ImplicitlyWait(new TimeSpan(0, 0, 30));
H.Button("//*[@id='X593']", driver); //click the ok button
element = wait.Until(ExpectedConditions.ElementIsVisible(By.ClassName("X967")));
H.Navigate("http://us14.chatzy.com/37785015405504", driver);
H.Button("//*[@id='X593']", driver); //click the enter room button
H.Button("//*[@id='X1049']", driver);
var chat = driver.FindElementById("X184");
// System.Collections.ObjectModel.ReadOnlyCollection<IWebElement> chat = driver.FindElementsByClassName("a");
// chat.ToString();
List<string> Temp = new List<string>();
Temp.Add(chat.Text);
System.IO.File.AppendAllLines(@"OUTPUT3.txt", Temp);
string[] t = System.IO.File.ReadAllLines(@"OUTPUT3.txt");
t.ToList();
// string s = chat.Text;
// string[] words = Regex.Split(s, "\r\n");
driver.Close();
}
示例9: Main
static void Main(string[] args)
{
var driver = new ChromeDriver(); // Should work in other Browser Drivers
string baseLink = "http://www.codeproject.com";
//foreach (var link in links)
for (int i = 2326; i > 2325; i--)
{
string link = baseLink + i.ToString();
driver.Navigate().GoToUrl(link);
try
{
var login = driver.FindElementById("Button1");
var uName = driver.FindElementByName("lname");
var pass = driver.FindElementByName("passw");
uName.SendKeys("admin");
pass.SendKeys("*******");
login.Submit();
}
catch
{
//already logged in
}
Screenshot ss = ((ITakesScreenshot)driver).GetScreenshot();
//Use it as you want now
string screenshot = ss.AsBase64EncodedString;
byte[] screenshotAsByteArray = ss.AsByteArray;
FileNameFromURL fileNameFromURL = new ConsoleApplication1.FileNameFromURL();
string filePath = Application.StartupPath + fileNameFromURL.ConvertToWindowsFileName(link) + ".jpg";
if (File.Exists(filePath))
{
File.Delete(filePath);
}
ss.SaveAsFile(filePath, ImageFormat.Png); //use any of the built in image formating
ss.ToString();//same as string screenshot = ss.AsBase64EncodedString;
}
//driver.Dispose();
driver.Close();
}
示例10: pullGamesHelper
private List<string> pullGamesHelper(ChromeDriver cd)
{
List<string> AllYourGames = new List<string>();
IWebElement e;
string purchaseTitle = "";
bool anotherRow = true;
int index = 0;
while (anotherRow)
{
index++;
try
{
e = cd.FindElementById("transactionDetailsRow-" + index);
e.Click();
System.Threading.Thread.Sleep(1000);
try
{
ReadOnlyCollection<IWebElement> roc = cd.FindElements(By.Id("itemTitle-0"));
foreach (IWebElement iwe in roc)
{
purchaseTitle = iwe.Text;
AllYourGames.Add(purchaseTitle);
}
cd.Navigate().Back();
System.Threading.Thread.Sleep(1000);
}
catch (Exception)
{
purchaseTitle = "This wasn't a game/movie";
cd.Navigate().Back();
System.Threading.Thread.Sleep(1000);
}
//AllYourGames.Add(purchaseTitle);
}
catch (Exception)
{
Console.WriteLine("The program has finished gathering the data...");
anotherRow = false;
}
}
cd.Close();
cd.Dispose();
return AllYourGames;
}
示例11: NaverCrawler
public NaverCrawler()
{
string id = ConfigurationManager.AppSettings["id"];
string password = ConfigurationManager.AppSettings["password"];
var processList = Process.GetProcessesByName("chromedriver");
foreach( var process in processList )
{
process.Kill();
}
var chromeDriverService = ChromeDriverService.CreateDefaultService();
chromeDriverService.HideCommandPromptWindow = true;
var option = new ChromeOptions();
option.AddExtension("3.7_0.crx");
driver = new ChromeDriver(chromeDriverService, option );
while (driver.WindowHandles.Count < 2)
{
Thread.Sleep(100);
}
driver.SwitchTo().Window(driver.WindowHandles[1]);
WebDriverWait _wait = new WebDriverWait(driver, new TimeSpan(0, 1, 0));
driver.Manage().Timeouts().ImplicitlyWait(new TimeSpan(0, 0, 10));
_wait.Until(d => d.FindElement(By.Id("user_email")));
driver.FindElementById("user_email").SendKeys(String.Format("{0}@naver.com\n", id));
_wait.Until(d => d.FindElement(By.Id("user_password")));
driver.FindElementById("user_password").SendKeys(password);
driver.FindElementById("loginbtn").Click();
driver.SwitchTo().Window(driver.WindowHandles[0]);
driver.Url = loginFormUrl;
driver.FindElementByCssSelector("#id").SendKeys(id);
driver.FindElementByCssSelector("#pw").SendKeys(password);
driver.FindElementByCssSelector("input.int_jogin").Click();
cookieContainer = new CookieContainer();
ReadOnlyCollection<OpenQA.Selenium.Cookie> cookieCollections = null;
bool sessionFound = false;
while (!sessionFound)
{
cookieCollections = driver.Manage().Cookies.AllCookies;
foreach( var cookie in cookieCollections )
{
if ( cookie.Name == "JSESSIONID" )
{
sessionFound = true;
break;
}
}
}
foreach( var cookie in cookieCollections )
{
cookieContainer.Add(new System.Net.Cookie(cookie.Name, cookie.Value, cookie.Path, cookie.Domain));
}
driver.Quit();
}
示例12: Run
static void Run(string[] args)
{
var chromeDriverPath = string.Concat(AppDomain.CurrentDomain.BaseDirectory, "driver");
bool enableCustomJustification = false;
string urlLogin = ConfigurationManager.AppSettings[CONFIG_PONTO_LOGIN_URL];
if (string.IsNullOrEmpty(urlLogin))
throw new InvalidOperationException(string.Format("Url de login do sistema de ponto não definida! Verifique a chave \"{0}\" no app.config.", CONFIG_PONTO_LOGIN_URL));
string username = ConfigurationManager.AppSettings[CONFIG_USERNAME];
if (string.IsNullOrEmpty(username))
throw new InvalidOperationException(string.Format("Nome de usuário não configurado! Verifique a chave \"{0}\" no app.config.", CONFIG_USERNAME));
string password = ConfigurationManager.AppSettings[CONFIG_PASSWORD];
if (string.IsNullOrEmpty(password))
throw new InvalidOperationException(string.Format("Senha de usuário não configurada! Verifique a chave \"{0}\" no app.config.", CONFIG_PASSWORD));
if (!bool.TryParse(ConfigurationManager.AppSettings[CONFIG_ENABLE_JUSTIFICATION], out enableCustomJustification))
enableCustomJustification = false;
string inputApontamento = string.Empty;
if (args == null || !args.Any())
{
Console.WriteLine("Informe o apontamento: 1-Entrada. 2-Início almoço. 3-Volta Almoço. 4-Saída.");
inputApontamento = Console.ReadLine();
}
else
{
inputApontamento = args[0];
}
Console.WriteLine("");
int apontamento = 0;
if (!int.TryParse(inputApontamento, out apontamento))
throw new InvalidOperationException(string.Format("Apontamento não definido corretamente. Valor informado: \"{0}\"! Utilize: 1-Entrada. 2-Início almoço. 3-Volta Almoço. 4-Saída.", inputApontamento));
using (var driver = new ChromeDriver(chromeDriverPath))
{
driver.Navigate().GoToUrl(urlLogin);
var usernameField = driver.FindElementById("ctl00_m_g_1f2f91c5_726b_47c3_a64d_34117653e0e4_ctl00_signInControl_UserName");
var passwordField = driver.FindElementById("ctl00_m_g_1f2f91c5_726b_47c3_a64d_34117653e0e4_ctl00_signInControl_Password");
var buttonLogin = driver.FindElementById("ctl00_m_g_1f2f91c5_726b_47c3_a64d_34117653e0e4_ctl00_signInControl_LoginButton");
usernameField.Clear();
usernameField.SendKeys(username);
passwordField.Clear();
passwordField.SendKeys(password);
buttonLogin.Click();
IWait<IWebDriver> firstWait = new WebDriverWait(driver, TimeSpan.FromSeconds(90));
firstWait.Until(x => driver.FindElementById("entrada") != null);
string btnApontamentoId = string.Empty;
switch ((Apontamento)apontamento)
{
case Apontamento.ENTRADA:
btnApontamentoId = "entrada";
break;
case Apontamento.INICIO_ALMOCO:
btnApontamentoId = "inicioAlmoco";
break;
case Apontamento.VOLTA_ALMOCO:
btnApontamentoId = "voltaAlmoco";
break;
case Apontamento.SAIDA:
btnApontamentoId = "saida";
break;
}
var btnApontamento = driver.FindElementById(btnApontamentoId);
btnApontamento.Click();
IWait<IWebDriver> secondWait = new WebDriverWait(driver, TimeSpan.FromSeconds(90));
secondWait.Until(x => driver.FindElementById("entrada") != null);
if ((Apontamento)apontamento == Apontamento.SAIDA)
{
try
{
driver.SwitchTo().DefaultContent();
var dialogIFrame = driver.FindElement(By.Id(""));
driver.SwitchTo().Frame(dialogIFrame);
var textAreaJustificativa = driver.FindElement(By.Id("ctl00_m_g_cac22e8d_9ad5_4163_b85d_7254c3524eac_ctl00_txtJustificativa"));
var btnConfirmarJustificativa = driver.FindElement(By.Id("ctl00_m_g_cac22e8d_9ad5_4163_b85d_7254c3524eac_ctl00_btnSalvar"));
string justificativa = ".";
if (enableCustomJustification)
{
//.........这里部分代码省略.........
示例13: pullGames
private int pullGames(string uname, string pword, string fpath)
{
string exePath = Application.ExecutablePath;
string[] path = exePath.Split('\\');
string cdPath = "";
for (int i = 0; i < path.Length - 1; i++)
cdPath += path[i] + "\\";
ChromeDriver cd;
try
{
cd = new ChromeDriver(cdPath);
}
catch (Exception)
{
Console.WriteLine("Put chromedriver in: " + cdPath);
return 2;
}
cd = login(cd, uname, pword);
//Now go to transaction summary page
System.Threading.Thread.Sleep(2000); // Give the page time to load
IWebElement e;
e = cd.FindElementById("transactionHistoryLink");
e.Click();
//Now change the date to 2010, since psplus has only been around since then
System.Threading.Thread.Sleep(2000); // Give the page time to load
e = cd.FindElementById("largeFilterStartInput");
e.Clear();
e.SendKeys("01/01/2010");
//Now update table
e = cd.FindElementById("largeFilterUpdateDateFilterButton");
e.Click();
System.Threading.Thread.Sleep(2000);
List<string> AllYourGames = new List<string>();
try
{
AllYourGames = pullGamesHelper(cd);
File.WriteAllLines(fpath + "\\PSPurchaseList.txt", AllYourGames);
return 0;
}
catch (Exception)
{
return 2;
}
}
示例14: BrowserTEst
public void BrowserTEst()
{
var drive2r = new ChromeDriver(@"d:\temp\");
// Initialize the Chrome Driver
using (var driver = new ChromeDriver(@"d:\temp\"))
{
// Go to the home page
driver.Navigate().GoToUrl("http://www.hkticketing.com/");
driver.FindElement(By.LinkText("Login/Register")).Click();
driver.FindElement(By.Id("email")).Clear();
driver.FindElement(By.Id("email")).SendKeys("[email protected]");
driver.FindElement(By.Id("login")).Click();
driver.FindElement(By.Id("uniform-login")).Click();
driver.FindElement(By.Id("pw")).Clear();
driver.FindElement(By.Id("pw")).SendKeys("xxxxx");
driver.FindElement(By.Id("login")).Click();
driver.Navigate().GoToUrl("https://www2.hkticketing.com/HKTWebApp/Booking.do?contentCode=MCCHEER0716&language=en_US");
// Get the page elements
var userNameField = driver.FindElementById("usr");
var userPasswordField = driver.FindElementById("pwd");
// Take a screenshot and save it into screen.png
driver.GetScreenshot().SaveAsFile(@"d:\temp\screen.png", ImageFormat.Png);
}
}
示例15: GetSearchBox
public IWebElement GetSearchBox(ChromeDriver driver)
{
return driver.FindElementById("search-box");
}