I wrote a class to automaticly translate text with selenium. When the translate button is pushed the page doesn't reload completly, I assume this happens with Javascript. I added a wait function to wait until the text shows up. However in 3 of the 10 generated translations I get the next error at line 30:
OpenQA.Selenium.WebDriverException: 'target frame detached (Session info: chrome=102.0.5005.115)'
Any solutions to fix it? thanks in advance!
class in c#
using System;
using System.Collections.Generic;
using System.Text;
using OpenQA.Selenium;
using OpenQA.Selenium.Support.UI;
using System.Threading;
namespace WebscraperBasic
{
[Serializable]
public class vertalenNu
{
public static String translateText(IWebDriver driver, String text, String languageSource, String languageDestination)
{
// nl - en - de - fr -es -it
driver.Url = "https://www.vertalen.nu/zinnen/";
driver.FindElement(By.Id("vertaaltxt")).SendKeys(text);
SelectElement testt = new SelectElement(driver.FindElement(By.Id("tselectfrom")));
testt.SelectByValue(languageSource);
SelectElement test = new SelectElement(driver.FindElement(By.Id("tselectto")));
test.SelectByValue(languageDestination);
driver.FindElement(By.XPath("//input[#title='Vertaal']")).Click();
String technicalSheettext;
try
{
WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(3));
wait.Until(driver => driver.FindElement(By.Id("resulttxt")).Text != "");
IWebElement technicalSheet = driver.FindElement(By.ClassName("mt-translation-content"));
technicalSheettext = technicalSheet.Text;
}
catch
{
technicalSheettext = "translation failed";
}
driver.Close();
driver.Quit();
return technicalSheettext;
}
}
}
Related
Hi everyone recently my mom created instagram account for his work and I want to make him auto follower bot in selenium but whenever I try to test this few times instagram just locks me out by saying Please try again in few minutes but It just keeps saying after 5-10-20 minutes even hours any suggestions ? How can I test this ?
With this code just logs in and scroll down in main page where you can follow people by randomly but I cant follow all of them , how can I adress follow button every time ?
using System;
using System.Collections.Generic;
using System.Threading;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.Support.UI;
namespace InstagramFollower
{
class Program
{
private static readonly string Pusername = "sorrycantshare";
private static readonly string Ppassword = "sorrycantshare";
private static int sayac = 1;
public static IWebDriver driver = new ChromeDriver();
static void Main()
{
WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(100));
driver.Navigate().GoToUrl("https://www.instagram.com/");
//driver.Manage().Window.Maximize();
Console.WriteLine("Siteye açıldı");
wait.Until(SeleniumExtras.WaitHelpers.ExpectedConditions.ElementIsVisible(By.Name("username")));
IWebElement username = driver.FindElement(By.Name("username"));
IWebElement password = driver.FindElement(By.Name("password"));
IWebElement loginbtn = driver.FindElement(By.CssSelector(".Igw0E.IwRSH.eGOV_._4EzTm"));
username.SendKeys(Pusername);
password.SendKeys(Ppassword);
loginbtn.Click();
Console.WriteLine("Hesaba giriş yapıldı");
ElementToClickableCssSelector(".sqdOP.L3NKy.y3zKF");
driver.Navigate().GoToUrl($"https://www.instagram.com");
Console.WriteLine("Anasayfaya yönlendirildi");
ElementToClickableCssSelector(".aOOlW.HoLwm");
IWebElement notNow = driver.FindElement(By.CssSelector(".aOOlW.HoLwm"));
notNow.Click();
IJavaScriptExecutor js = (IJavaScriptExecutor)driver;
js.ExecuteScript("window.scrollTo(0, document.body.scrollHeight);");
Thread.Sleep(1500);
js.ExecuteScript("window.scrollTo(0, document.body.scrollHeight);");
Thread.Sleep(2500);
ElementToClickableCssSelector(".Szr5J._6CZji");
Listpeople();
Thread.Sleep(3500);
/*
IWebElement followbtn = driver.FindElement(By.CssSelector(".sqdOP.L3NKy._4pI4F.y3zKF"));
followbtn.Click(); // It follows first person on line but It gives error for others.
*/
}
public static void Listpeople()
{
IReadOnlyCollection<IWebElement> followersname = driver.FindElements(By.CssSelector(".FPmhX.notranslate.Qj3-a"));
IWebElement nextbtn = driver.FindElement(By.CssSelector(".Szr5J._6CZji"));
foreach (IWebElement follower in followersname)
{
Console.WriteLine(sayac.ToString() + " ==> " + follower.Text);
sayac++;
if (sayac == 8)
{
nextbtn.Click();
}
}
}
public static void ElementToClickableCssSelector(string target)
{
WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(100));
wait.Until(SeleniumExtras.WaitHelpers.ExpectedConditions.ElementToBeClickable(By.CssSelector(target)));
}
}
}
Well I had to read some topics about it turns out instagram detects selenium webdriver but I belive in my case is different.Reason I got error of please try again in later is beacuse my account does not log out , every time I log in and test after I stop building and shutdown cmd and browser so It doesnt log out.I am now writing a void to log out for after I test it
I am trying to make a bot that goes through drop-downs and makes selections but it's having trouble finding the element. The code is below.
using System;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.Support.Extensions;
using OpenQA.Selenium.Support.UI;
namespace selenium_test
{
class Program
{
static void Main(string[] args)
{
IWebDriver driver;
driver = new ChromeDriver("C:\\");
Console.WriteLine("ChromeDriver Initialized");
driver.Url = "https://odyssey.gwinnettcourts.com/Portal/Home/Dashboard/26";
IWebElement typeElement = driver.FindElement(By.XPath(".//option[#id='cboHSSearchBy']"));
var typeSelect = new SelectElement(typeElement);
typeSelect.SelectByValue("JudicialOfficer");
typeElement.Click();
}
}
}
what exactly is the error? I can only assume that it is taking time to find element.
add wait time maybe? also, why using xpath when you have id of controls? id is quicker!
new WebDriverWait(driver, TimeSpan.FromSeconds(10)).Until(SeleniumExtras.WaitHelpers.ExpectedConditions.ElementExists((By.Id("cboHSSearchBy"))));
I'm using the Page Object model to design some selenium tests. I'm having a few issues with the wait code in my keywords below. When I call the keyword in my NUnit test using code such as below it trys to click on the button before it is ready. If I paste the same wait code in the NUnit test itself it waits as expected and then clicks the button. My preference would have all the keywords I implement to take care of the waits and not have to write it in my test. Am I missing something here?
NUnit Test
public void QuotesPageTest()
{
//Loginto CRM
LoginPage loginPage = new LoginPage();
loginPage.UserLogin();
//Select quotes tile
pgCommon myMenu = new pgCommon();
myMenu.GoToMenu("quotes");
//Click new
pgQuotes QuotesPage = new pgQuotes();
Keywords.DoSendKeys(QuotesPage.btnNew);
}
Keywords.cs
using OpenQA.Selenium;
using OpenQA.Selenium.Support.UI;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TraingDay1_1
{
public static class Keywords
{
public static void DoSendKeys(this IWebElement element)
{
String elementName = element.GetAttribute("value");
WebDriverWait wait = new WebDriverWait(GlobalDriver.driver, TimeSpan.FromSeconds(EnvironmentData.objectTimeout));
wait.Until(ExpectedConditions.ElementToBeClickable(element));
element.SendKeys(Keys.Enter);
Console.WriteLine("Selected " + elementName + " and pressed enter key");
}
public static void DoClick(this IWebElement element)
{
String elementName = element.GetAttribute("value");
WebDriverWait wait = new WebDriverWait(GlobalDriver.driver, TimeSpan.FromSeconds(EnvironmentData.objectTimeout));
wait.Until(ExpectedConditions.ElementToBeClickable(element));
element.Click();
Console.WriteLine("Selected " + elementName + " and pressed enter key");
}
I am new to selenium, currently exploring on how it works. Started using it for ASP.NET application, i am using C# Selenium driver, IE Driver server ( 32 bit as it's faster than 64 bit)
I navigated to a application there I am clicking a link which should take me to ANOTHER WEBSITE where I have to find a textbox and clear it and enter some text (SendKeys) and then click a button.
When it goes to a another website from main website, It's unable to find the element ( I tried using by.ID and by.Name). I made sure element is available on the webpage. As recommened I used ImplicitlyWait but no luck, tried thread.sleep() no lucK.. Does the test needs to be on the same website which launched initially ?.. Below is my code snippet.. Please help me..
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using OpenQA.Selenium;
using OpenQA.Selenium.IE;
using OpenQA.Selenium.Support.UI;
using System.Threading;
namespace mySelenium
{
class Program
{
private static void Main(string[] args)
{
IWebDriver driver = new InternetExplorerDriver(#"C:\Users\msbyuva\Downloads\IEDriverServer_Win32_2.45.0\");
driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(10));
driver.Navigate().GoToUrl("http://MyorgName.org/Apps/Sites/2015/login.aspx");
IWebElement userNameTxtBox = driver.FindElement(By.Id("ContentPlaceHolder1_Login1_UserName"));
userNameTxtBox.SendKeys("MSBYUVA");
IWebElement passwordTxtBox = driver.FindElement(By.Id("ContentPlaceHolder1_Login1_Password"));
passwordTxtBox.SendKeys("1234");
var myButton = driver.FindElement(By.Id("ContentPlaceHolder1_Login1_LoginButton"));
myButton.Click();
var EMailLink = driver.FindElement(By.LinkText("Email Testing Link"));
EMailLink .Click();
//Thread.Sleep(10000);
// -- HERE IT IS THROWING ERROR (ANOTHER WEBSITE AFTER CLICKING HYPERLINK)
var toEmailAddress = driver.FindElement(By.Name("ctl00$ContentPlaceHolder1$txtTo"));
toEmailAddress.Clear();
toEmailAddress.SendKeys("msbyuva#gmail.com");
var chkEmailAttachment = driver.FindElement(By.Name("ctl00$ContentPlaceHolder1$ChkAttachMent"));
chkEmailAttachment.Click();
var sendEmailButton = driver.FindElement(By.Id("ctl00_ContentPlaceHolder1_BtnSend"));
sendEmailButton.Click();
}
}
}
You need to switchTo newly opened window and set focus to it in order to send any commands to it
string currentHandle = driver.CurrentWindowHandle;
driver.SwitchTo().Window(driver.WindowHandles.ToList().Last());
After you done with newly opened window do(as need)
driver.Close();
driver.SwitchTo().Window(currentHandle );
More perfectly use PopupWindowFinder class
string currentHandle = driver.CurrentWindowHandle;
PopupWindowFinder popUpWindow = new PopupWindowFinder(driver);
string popupWindowHandle = popUpWindow.Click(EMailLink );
driver.SwitchTo().Window(popupWindowHandle);
//then do the email stuff
var toEmailAddress = driver.FindElement(By.Name("ctl00$ContentPlaceHolder1$txtTo"));
toEmailAddress.Clear();
toEmailAddress.SendKeys("msbyuva#gmail.com");
var chkEmailAttachment = driver.FindElement(By.Name("ctl00$ContentPlaceHolder1$ChkAttachMent"));
chkEmailAttachment.Click();
var sendEmailButton = driver.FindElement(By.Id("ctl00_ContentPlaceHolder1_BtnSend"));
sendEmailButton.Click();
}
}
}
//closing pop up window
driver.Close();
driver.SwitchToWindow(currentHandle);
Due to the lack of proper documentation, I'm not sure if HtmlAgilityPack supports screen capture in C# after it loads the html contents.
So is there a way I can more or less grab a screenshot using (or along with) HtmlAgilityPack so I can have a visual clue as to what happens every time I do page manipulations?
Here is my working code so far:
using HtmlAgilityPack;
using System;
namespace ConsoleApplication4
{
class Program
{
static void Main(string[] args)
{
string urlDemo = "https://htmlagilitypack.codeplex.com/";
HtmlWeb getHtmlWeb = new HtmlWeb();
var doc = getHtmlWeb.Load(urlDemo);
var sentence = doc.DocumentNode.SelectNodes("//p");
int counter = 1;
try
{
foreach (var p in sentence)
{
Console.WriteLine(counter + ". " + p.InnerText);
counter++;
}
}
catch (Exception e)
{
Console.WriteLine(e);
}
Console.ReadLine();
}
}
}
Currently, it scrapes and output all the p of the page in the console but at the same time I want to get a screen grab of the scraped contents but I don't know how and where to begin.
Any help is greatly appreciated. TIA
You can't do this with HTML Agility Pack. Use a different tool such as Selenium WebDriver. Here is how to do it: Take a screenshot with Selenium WebDriver
Could you use Selenium WebDriver instead?
You'll need to add the following NuGet packages to your project first:
Selenium.WebDriver
Selenium.Support
Loading a page and taking a screenshot is then as simple as...
using System;
using System.Drawing.Imaging;
using System.IO;
using OpenQA.Selenium;
using OpenQA.Selenium.Firefox;
using OpenQA.Selenium.Support.UI;
namespace SeleniumTest
{
class Program
{
static void Main(string[] args)
{
// Create a web driver that used Firefox
var driver = new FirefoxDriver(
new FirefoxBinary(), new FirefoxProfile(), TimeSpan.FromSeconds(120));
// Load your page
driver.Navigate().GoToUrl("http://google.com");
// Wait until the page has actually loaded
var wait = new WebDriverWait(driver, new TimeSpan(0, 0, 10));
wait.Until(d => d.Title.Contains("Google"));
// Take a screenshot, and saves it to a file (you must have full access rights to the save location).
var myDesktop = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
((ITakesScreenshot)driver).GetScreenshot().SaveAsFile(Path.Combine(myDesktop, "google-screenshot.png"), ImageFormat.Png);
driver.Close();
}
}
}