GVKun编程网logo

由于“此浏览器或应用可能不安全,”无法使用Selenium自动化登录google。

15

本文将介绍由于“此浏览器或应用可能不安全,”无法使用Selenium自动化登录google。的详细情况,。我们将通过案例分析、数据研究等多种方式,帮助您更全面地了解这个主题,同时也将涉及一些关于C#利

本文将介绍由于“此浏览器或应用可能不安全,”无法使用Selenium自动化登录google。的详细情况,。我们将通过案例分析、数据研究等多种方式,帮助您更全面地了解这个主题,同时也将涉及一些关于C# 利用Selenium实现浏览器自动化操作、C# 利用Selenium实现浏览器自动化操作的示例代码、cucumber; Selenium WebDriver-如何使用Google Chrome浏览器代替Firefox作为测试浏览器、Firefox更新后无法使用Selenium打开浏览器的知识。

本文目录一览:

由于“此浏览器或应用可能不安全,”无法使用Selenium自动化登录google。

由于“此浏览器或应用可能不安全,”无法使用Selenium自动化登录google。

我正在尝试使用selenium登录到google,但不断收到错误消息“此浏览器或应用可能不安全”。

我用来登录的功能是:

async function loginToChrome(driver, username, password) {  await driver.get("https://accounts.google.com/signin");  await driver.sleep(1000);  let email_phone = await driver.findElement(    By.xpath("//input[@id=''identifierId'']")  );  await email_phone.sendKeys(username);  await driver.findElement(By.id("identifierNext")).click();  await driver.sleep(1000);  let passEl = await driver.findElement(By.xpath("//input[@name=''password'']"));  await passEl.sendKeys(password);  await driver.findElement(By.id("passwordNext")).click();  await driver.sleep(1000);}

我尝试使用chrome和firefox网络驱动程序,但均无法正常工作。我也尝试过这样做.excludeSwitches([''enable-automation''])也没有帮助。

这使我认为登录页面也许可以检测到我在自动化环境中运行。我尝试过这种解决方案,该解决方案使该应用程序[无法在Web驱动程序中运行:网站可以检测到您何时在chromedriver中使用selenium?
我也调查了User-Agent看是否是问题所在,但是发现它与我的常规Chrome相同。

所有这些都没有奏效,这使我陷入困境。我已经看到了一些解决方案,这些解决方案说使用正常安装的chrome中已经创建的用户个人资料,但这不适用于我的用例。

有没有人找到解决方案?我一直在寻找时间,空手而归。

编辑:
似乎最近这已经引起了很多关注。我找到了一个解决方案,使我可以继续使用自动化客户端,而不会遇到太多问题。切换到Puppeteer。查看以下软件包:

    "puppeteer",    "puppeteer-extra",    "puppeteer-extra-plugin-stealth"

答案1

小编典典

此错误消息…

This browser or app may not be secure.Try using a different browser. If you’re already using a supported browser, you can refresh your screen and try again to sign in.

…表示 WebDriver 无法验证 浏览上下文,浏览器 会话。


潜在原因和解决方案

导致此错误的原因可能有多种,如下所示:

  • @Raphael Schaad在尝试在桌面应用程序上用Google登录时出现“此浏览器或应用程序可能不安全”的错误消息中提到,如果用户可以使用其他Google帐户登录就可以正常使用同一应用程序,则必须解决此问题说谎与特定的帐户。可能的原因是,这是用户使用 “双重身份验证” 的唯一帐户。
  • 另一个潜在的原因可能是使用不太安全的应用程序。如果某个应用或网站不符合google-chrome的安全标准,则Google可能会阻止任何尝试登录该帐户的人。安全性较低的应用程序可能会使黑客更容易进入您的帐户,因此阻止这些应用程序的登录有助于确保您的帐户安全。

在这些情况下,相应的解决方案是:

  • 禁用此Google帐户的 两因素身份验证 ,然后执行 @Test
  • 允许安全性较低的应用

tl; 博士

几个相关的事件文档:

  • 使用受支持的浏览器登录

C# 利用Selenium实现浏览器自动化操作

C# 利用Selenium实现浏览器自动化操作

概述

Selenium是一款免费的分布式的自动化测试工具,支持多种开发语言,无论是C、 java、ruby、python、或是C# ,你都可以通过selenium完成自动化测试。本文以一个简单的小例子,简述C# 利用Selenium进行浏览器的模拟操作,仅供学习分享使用,如有不足之处,还请指正。

涉及知识点

要实现本例的功能,除了要掌握Html ,JavaScript,CSS等基础知识,还涉及以下知识点:

  • log4net:主要用于日志的记录和存储,本例采用log4net进行日志记录,便于过程跟踪和问题排查,关于log4net的配置和介绍,之前已有说明,本文不做赘述。
  • Queue:队列,先进先出模式,本文主要用于将日志信息保存于队列中,然后再显示到页面上,其中Enqueue用于添加内容到结尾处,Dequeue用于返回并移除一个位置的对象。
  • IWebDriver:浏览器驱动接口,所有的关于浏览器的操作都可以通过此接口进行,不同浏览器有不同的实现类,如:IE浏览器(InternetExplorerDriver)Chrome浏览器(ChromeDriver)等。
  • BackgroundWorker:后台工作线程,区别于主线程,通过事件触发不同的状态。

Selenium安装

本例开发工具为VS2019,通过NuGet进行需要的软件包的安装与管理,如下所示:

示例效果图

本例采用Chrome浏览器,用于监控某一个网站并获取相应内容,如下所示:

Selenium示例介绍

定义一个webDriver,如下所示:

1 //谷歌浏览器
2 ChromeOptions options = new ChromeOptions();
3 this.driver = new ChromeDriver(options);

通过ID获取元素并填充内容和触发事件,如下所示:

this.driver.FindElement(By.Id("email")).SendKeys(username);
2 password)).SendKeys(password);
# 7. 点击登录按钮
4 sign-in")).Click();

通过XPath获取元素,如下所示:

string xpath1 = //div[@class=\"product-list\"]/div[@class=\"product\"]/div[@class=\"price-and-detail\"]/div[@class=\"price\"]/span[@class=\"noStock\"];
string txt = this.driver.FindElement(By.XPath(xpath1)).Text;

核心代码

主要的核心代码,就是浏览器的元素定位查找和事件触发,如下所示:

  1 using OpenQA.Selenium;
  2  OpenQA.Selenium.IE;
  3  OpenQA.Selenium.Chrome;
  4  System;
  5  System.Collections.Generic;
  6  System.Linq;
  7  System.Text;
  8  System.Threading;
  9  System.Threading.Tasks;
 10 
 11 namespace AiSmoking.Core
 12 {
 13     public class Smoking
 14     {
 15         /// <summary>
 16         /// 是否正在运行
 17         </summary>
 18         private bool running = false 19 
 20          21          驱动
 22          23         private IWebDriver driver = null 24 
 25 
 26          27          # 无货
 28          29         string no_stock = Currently Out of Stock 30 
 31 
 32          33            # 线程等待秒数
 34          35         int wait_sec = 2 36 
 37         private Dictionary<string,string> cfg_info;
 38 
 39         string work_path = string.Empty;
 40 
 41          42          构造函数
 43          44         public Smoking()
 45         {
 46 
 47         }
 48 
 49          50          带参构造函数
 51          52         <param name="cfg_info"></param>
 53         <param name="work_path"></param>
 54         public Smoking(Dictionary<string> cfg_info,1)"> work_path)
 55  56             this.cfg_info = 57             this.work_path = work_path;
 58             this.wait_sec = int.Parse(cfg_info[wait_sec]);
 59             # 如果小于2,则等于2
 60             this.wait_sec = (this.wait_sec < 2 ? 2 : this.wait_sec);
 61             this.wait_sec * 1000 62  63 
 64          65          开始跑
 66          67         void startRun()
 68  69             """运行起来"""
 70             try
 71             {
 72                 this.running = true 73                 string url = this.cfg_info[url];
 74                 string username = username 75                 string password =  76                 string item_id = item_id 77                 if (string.IsNullOrEmpty(url) || string.IsNullOrEmpty(username) || string.IsNullOrEmpty(password) || .IsNullOrEmpty(item_id))
 78                 {
 79                     LogHelper.put(配置信息不全,请检查config.cfg文件是否为空,然后再重启);
 80                     return 81                 }
 82                 this.driver == )
 83  84                     string explorer = explorer 85                     if (explorer == Chrome 86                     {
 87                          88                         ChromeOptions options =  89                          ChromeDriver(options);
 90                     }
 91                     else
 92  93                         默认IE
 94                         var options =  InternetExplorerOptions();
 95                         options.AddAdditionalCapability.(''encoding=UTF-8'')
 96                         options.add_argument(''Accept= text / css,* / *'')
 97                         options.add_argument(''Accept - Language= zh - Hans - CN,zh - Hans;q = 0.5'')
 98                         options.add_argument(''Accept - Encoding= gzip,deflate'')
 99                         options.add_argument(''user-agent=Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; rv:11.0) like Gecko'')
100                         # 2. 定义浏览器驱动对象
101                          InternetExplorerDriver(options);
102 103 104                 .run(url,username,password,item_id);
105             }
106             catch (Exception e)
107 108                 LogHelper.put(运行过程中出错,请重新打开再试"+e.StackTrace);
109 110 111 
112 
113         114          运行
115         116         <param name="url"></param>
117         <param name="username"></param>
118         <param name="password"></param>
119         <param name="item_id"></param>
120         void run(string url,1)">string username,1)">string password,1)"> item_id)
121 122             """运行起来"""
123             # 3. 访问网站
124             .driver.Navigate().GoToUrl(url);
125             # 4. 最大化窗口
126             .driver.Manage().Window.Maximize();
127             this.checkIsExists(By.LinkText(账户登录)))
128 129                 # 判断是否登录:未登录
130                 .login(username,password);
131 132             this.checkIsExists(By.PartialLinkText(欢迎回来133 134                 # 判断是否登录:已登录
135                 LogHelper.put(登录成功,下一步开始工作了136                 .working(item_id);
137 138             139 140                 LogHelper.put(登录失败,请设置账号密码141 142 143 
144         145          停止运行
146         147          stopRun()
148 149             """停止"""
150             151 152                 153                 # 如果驱动不为空,则关闭
154                 self.close_browser_nicely(self.__driver)
155                 this.driver != 156 157                     .driver.Quit();
158                     # 关闭后切要为None,否则启动报错
159                     160 161 162             163 164                 print(''Stop Failure'')
165 166             finally
167 168                 169 170 171 
172 
173         void login( password)
174 175             # 5. 点击链接跳转到登录页面
176             this.driver.FindElement(By.LinkText()).Click();
177             # 6. 输入账号密码
178             # 判断是否加载完成
179             this.checkIsExists(By.Id(180 181                 182                 183                 184                 185 186 187 
188         189          工作状态
190         191         192         void working(193 194             while (.running)
195 196                 197 198                     # 正常获取信息
199                     string200 201                         )).Clear();
202                         )).SendKeys(item_id);
203                         )).SendKeys(Keys.Enter);
204 205                     # 判断是否查询到商品
206                     string xpath = //div[@class=\"specialty-header search\"]/div[@class=\"specialty-description\"]/div[@class=\"gt-450\"]/span[2] 207                     .checkIsExists(By.XPath(xpath)))
208 209                         int count = int.Parse(.driver.FindElement(By.XPath(xpath)).Text);
210                         if (count < 1211                         {
212                             Thread.Sleep(213                             LogHelper.put(没有查询到item id =" + item_id + 对应的信息214                             continue215                         }
216 217                     218 219                         Thread.Sleep(220                         LogHelper.put(没有查询到item id2 =221                         222 223                     # 判断当前库存是否有货
224 
225                     226                     .checkIsExists(By.XPath(xpath1)))
227 228                         .driver.FindElement(By.XPath(xpath1)).Text;
229                         if (txt == .no_stock)
230 231                             # 当前无货
232                             Thread.Sleep(233                             LogHelper.put(查询一次,无货234                             235 236 237                     # 链接path1
238                     string xpath2 = //div[@class=\"product-list\"]/div[@class=\"product\"]/div[@class=\"imgDiv\"]/a239                     # 判断是否加载完毕
240                     # this.waiting((By.CLASS_NAME,"imgDiv"))
241                     .checkIsExists(By.XPath(xpath2)))
242 243                         .driver.FindElement(By.XPath(xpath2)).Click();
244                         Thread.Sleep(245                         # 加入购物车
246                         this.checkIsExists(By.ClassName(add-to-cart247 248                             this.driver.FindElement(By.ClassName(249                             LogHelper.put(加入购物车成功,商品item-id:" + item_id);
250                             break251 252                         253 254                             LogHelper.put(未找到加入购物车按钮255 256 257                     258 259                         LogHelper.put(没有查询到,可能是商品编码不对,或者已下架260 261                     Thread.Sleep(262 263                 264 265                     Thread.Sleep(266                     LogHelper.put(e);
267 268 269 270 
271         272          判断是否存在
273         274         <param name="by"></param>
275         <returns></returns>
276         bool checkIsExists(By by)
277 278             279 280                 int i = 0281                 this.running && i < 3282 283                     this.driver.FindElements(by).Count > 284 285                         286 287                     288 289                         Thread.Sleep(290                         i = i + 291 292 293                 return 294 295             296 297                 LogHelper.put(e);
298                 299 300 301 
302     }
303 }
View Code

关于日志帮助类,代码如下:

 1  2  3  4  5  6  log4net;
 7 
 8 [assembly: log4net.Config.XmlConfigurator(Watch = )]
 9 10 11     12      日志帮助类
13     14     static  LogHelper
15 16         17          日志实例
18         19         static ILog logInstance = LogManager.GetLogger(smoking20 
21         static Queue<string> queue = new Queue<string>(200022 
23         void put( msg)
24 25             queue.Enqueue(msg);
26             WriteLog(msg,LogLevel.Info);
27 28 
29          put(Exception ex)
30 31             WriteLog(ex.StackTrace,LogLevel.Error);
32 33 
34         string get()
35 36             if (queue.Count > 37 38                  queue.Dequeue();
39 40             41 42                 43 44 45 
46         void WriteLog( message,LogLevel level)
47 48             switch (level)
49 50                 case LogLevel.Debug:
51                     logInstance.Debug(message);
52                     53                  LogLevel.Error:
54                     logInstance.Error(message);
55                     56                  LogLevel.Fatal:
57                     logInstance.Fatal(message);
58                     59                  LogLevel.Info:
60                     logInstance.Info(message);
61                     62                  LogLevel.Warn:
63                     logInstance.Warn(message);
64                     65                 default:
66 67                     68 69 70 
71 
72 73 
74 
75     enum LogLevel
76 77         Debug = ,78         Error = 79         Fatal = 80         Info = 81         Warn = 4
82 83 }
View Code

关于log4net的实例定义,需要由配置文件【Log4NetConfig.xml】支撑,如下所示:

 

<?xml version="1.0" encoding="utf-8" ?>
<log4net>
 3     root 4         level value="DEBUG" />
 5         appender-ref ref="LogFileAppender"  6         ="ConsoleAppender"  7     </ 8     logger name="smoking" 9         ="ALL" 10     logger11     appender ="LogFileAppender" type="log4net.Appender.FileAppender" 12         param ="File" value="logs/${TMO}log-file.txt" 13         StaticLogFileName ="false"14         ="AppendToFile"="true" 15         layout type="log4net.Layout.PatternLayout"16             ="Header"="[Header]"17             ="Footer"="[Footer]"18             ="ConversionPattern"="%d [%t] %-5p %c [%x]  - %m%n"layout20         filter ="log4net.Filter.LevelRangeFilter"21             ="LevelMin"22             ="LevelMax"="ERROR" filter24     appender25     ="ConsoleAppender"="log4net.Appender.ConsoleAppender" 26         27             ="%d [%t] %-5p %c [%x] - %m%n" 28         29     >
View Code

 还需要在AssemblyInfo.cs中添加声明,如下所示:

1 [assembly: log4net.Config.DOMConfigurator(ConfigFile = Log4NetConfig.xml",ConfigFileExtension = xmltrue)]

备注

行路难·其一

【作者】李白 【朝代】唐

金樽清酒斗十千,玉盘珍羞直万钱。

停杯投箸不能食,拔剑四顾心茫然。

欲渡黄河冰塞川,将登太行雪满山。

闲来垂钓碧溪上,忽复乘舟梦日边。

行路难,行路难,多歧路,今安在?

长风破浪会有时,直挂云帆济沧海。 

总结

以上是小编为你收集整理的C# 利用Selenium实现浏览器自动化操作全部内容。

如果觉得小编网站内容还不错,欢迎将小编网站推荐给好友。

C# 利用Selenium实现浏览器自动化操作的示例代码

C# 利用Selenium实现浏览器自动化操作的示例代码

概述

Selenium是一款免费的分布式的自动化测试工具,支持多种开发语言,无论是C、 java、ruby、python、或是C# ,你都可以通过selenium完成自动化测试。本文以一个简单的小例子,简述C# 利用Selenium进行浏览器的模拟操作,仅供学习分享使用,如有不足之处,还请指正。

涉及知识点

要实现本例的功能,除了要掌握Html ,JavaScript,CSS等基础知识,还涉及以下知识点:

  • log4net:主要用于日志的记录和存储,本例采用log4net进行日志记录,便于过程跟踪和问题排查,关于log4net的配置和介绍,之前已有说明,本文不做赘述。
  • Queue:队列,先进先出模式,本文主要用于将日志信息保存于队列中,然后再显示到页面上,其中Enqueue用于添加内容到结尾处,Dequeue用于返回并移除一个位置的对象。
  • IWebDriver:浏览器驱动接口,所有的关于浏览器的操作都可以通过此接口进行,不同浏览器有不同的实现类,如:IE浏览器(InternetExplorerDriver)Chrome浏览器(ChromeDriver)等。
  • BackgroundWorker:后台工作线程,区别于主线程,通过事件触发不同的状态。

Selenium安装

本例开发工具为VS2019,通过NuGet进行需要的软件包的安装与管理,如下所示:

示例效果图

本例采用Chrome浏览器,用于监控某一个网站并获取相应内容,如下所示:

Selenium示例介绍

定义一个webDriver,如下所示:

//谷歌浏览器
 ChromeOptions options = new ChromeOptions();
 this.driver = new ChromeDriver(options);

通过ID获取元素并填充内容和触发事件,如下所示:

this.driver.FindElement(By.Id("email")).SendKeys(username);
this.driver.FindElement(By.Id("password")).SendKeys(password);
 //# 7. 点击登录按钮
this.driver.FindElement(By.Id("sign-in")).Click();

通过XPath获取元素,如下所示:

string xpath1 = "//div[@class=\"product-list\"]/div[@class=\"product\"]/div[@class=\"price-and-detail\"]/div[@class=\"price\"]/span[@class=\"noStock\"]";
string txt = this.driver.FindElement(By.XPath(xpath1)).Text;

核心代码

主要的核心代码,就是浏览器的元素定位查找和事件触发,如下所示:

using OpenQA.Selenium;
using OpenQA.Selenium.IE;
using OpenQA.Selenium.Chrome;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace AiSmoking.Core
{
  public class Smoking
  {
    /// <summary>
    /// 是否正在运行
    /// </summary>
    private bool running = false;

    /// <summary>
    /// 驱动
    /// </summary>
    private IWebDriver driver = null;


    /// <summary>
    /// # 无货
    /// </summary>
    private string no_stock = "Currently Out of Stock";


    /// <summary>
    ///  # 线程等待秒数
    /// </summary>
    private int wait_sec = 2;

    private Dictionary<string, string> cfg_info;

    private string work_path = string.Empty;

    /// <summary>
    /// 构造函数
    /// </summary>
    public Smoking()
    {

    }

    /// <summary>
    /// 带参构造函数
    /// </summary>
    /// <param name="cfg_info"></param>
    /// <param name="work_path"></param>
    public Smoking(Dictionary<string, string> cfg_info,string work_path)
    {
      this.cfg_info = cfg_info;
      this.work_path = work_path;
      this.wait_sec = int.Parse(cfg_info["wait_sec"]);
      //# 如果小于2,则等于2
      this.wait_sec = (this.wait_sec < 2 ? 2 : this.wait_sec);
      this.wait_sec = this.wait_sec * 1000;
    }

    /// <summary>
    /// 开始跑
    /// </summary>
    public void startRun()
    {
      //"""运行起来"""
      try
      {
        this.running = true;
        string url = this.cfg_info["url"];
        string username = this.cfg_info["username"];
        string password = this.cfg_info["password"];
        string item_id = this.cfg_info["item_id"];
        if (string.IsNullOrEmpty(url) || string.IsNullOrEmpty(username) || string.IsNullOrEmpty(password) || string.IsNullOrEmpty(item_id))
        {
          LogHelper.put("配置信息不全,请检查config.cfg文件是否为空,然后再重启");
          return;
        }
        if (this.driver == null)
        {
          string explorer = this.cfg_info["explorer"];
          if (explorer == "Chrome")
          {
            //谷歌浏览器
            ChromeOptions options = new ChromeOptions();
            this.driver = new ChromeDriver(options);
          }
          else
          {
            //默认IE
            var options = new InternetExplorerOptions();
            //options.AddAdditionalCapability.(''encoding=UTF-8'')
            //options.add_argument(''Accept= text / css, * / *'')
            //options.add_argument(''Accept - Language= zh - Hans - CN, zh - Hans;q = 0.5'')
            //options.add_argument(''Accept - Encoding= gzip, deflate'')
            //options.add_argument(''user-agent=Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; rv:11.0) like Gecko'')
            //# 2. 定义浏览器驱动对象
            this.driver = new InternetExplorerDriver(options);
          }
        }
        this.run(url, username, password, item_id);
      }
      catch (Exception e)
      {
        LogHelper.put("运行过程中出错,请重新打开再试"+e.StackTrace);
      }
    }


    /// <summary>
    /// 运行
    /// </summary>
    /// <param name="url"></param>
    /// <param name="username"></param>
    /// <param name="password"></param>
    /// <param name="item_id"></param>
    private void run(string url, string username, string password, string item_id)
    {
      //"""运行起来"""
      //# 3. 访问网站
      this.driver.Navigate().GoToUrl(url);
      //# 4. 最大化窗口
      this.driver.Manage().Window.Maximize();
      if (this.checkIsExists(By.LinkText("账户登录")))
      {
        //# 判断是否登录:未登录
        this.login(username, password);
      }
      if (this.checkIsExists(By.PartialLinkText("欢迎回来")))
      {
        //# 判断是否登录:已登录
        LogHelper.put("登录成功,下一步开始工作了");
        this.working(item_id);
      }
      else
      {
        LogHelper.put("登录失败,请设置账号密码");
      }
    }

    /// <summary>
    /// 停止运行
    /// </summary>
    public void stopRun()
    {
      //"""停止"""
      try
      {
        this.running = false;
        //# 如果驱动不为空,则关闭
        //self.close_browser_nicely(self.__driver)
        if (this.driver != null)
        {
          this.driver.Quit();
          //# 关闭后切要为None,否则启动报错
          this.driver = null;
        }
      }
      catch (Exception e)
      {
        //print(''Stop Failure'')
      }
      finally
      {
        this.driver = null;
      }
    }


    private void login(string username, string password)
    {
      //# 5. 点击链接跳转到登录页面
      this.driver.FindElement(By.LinkText("账户登录")).Click();
      //# 6. 输入账号密码
      //# 判断是否加载完成
      if (this.checkIsExists(By.Id("email")))
      {
        this.driver.FindElement(By.Id("email")).SendKeys(username);
        this.driver.FindElement(By.Id("password")).SendKeys(password);
        //# 7. 点击登录按钮
        this.driver.FindElement(By.Id("sign-in")).Click();
      }
    }

    /// <summary>
    /// 工作状态
    /// </summary>
    /// <param name="item_id"></param>
    private void working(string item_id)
    {
      while (this.running)
      {
        try
        {
          //# 正常获取信息
          if (this.checkIsExists(By.Id("string")))
          {
            this.driver.FindElement(By.Id("string")).Clear();
            this.driver.FindElement(By.Id("string")).SendKeys(item_id);
            this.driver.FindElement(By.Id("string")).SendKeys(Keys.Enter);
          }
          //# 判断是否查询到商品
          string xpath = "//div[@class=\"specialty-header search\"]/div[@class=\"specialty-description\"]/div[@class=\"gt-450\"]/span[2] ";
          if (this.checkIsExists(By.XPath(xpath)))
          {
            int count = int.Parse(this.driver.FindElement(By.XPath(xpath)).Text);
            if (count < 1)
            {
              Thread.Sleep(this.wait_sec);
              LogHelper.put("没有查询到item id =" + item_id + "对应的信息");
              continue;
            }
          }
          else
          {
            Thread.Sleep(this.wait_sec);
            LogHelper.put("没有查询到item id2 =" + item_id + "对应的信息");
            continue;
          }
          //# 判断当前库存是否有货

          string xpath1 = "//div[@class=\"product-list\"]/div[@class=\"product\"]/div[@class=\"price-and-detail\"]/div[@class=\"price\"]/span[@class=\"noStock\"]";
          if (this.checkIsExists(By.XPath(xpath1)))
          {
            string txt = this.driver.FindElement(By.XPath(xpath1)).Text;
            if (txt == this.no_stock)
            {
              //# 当前无货
              Thread.Sleep(this.wait_sec);
              LogHelper.put("查询一次" + item_id + ",无货");
              continue;
            }
          }
          //# 链接path1
          string xpath2 = "//div[@class=\"product-list\"]/div[@class=\"product\"]/div[@class=\"imgDiv\"]/a";
          //# 判断是否加载完毕
          //# this.waiting((By.CLASS_NAME, "imgDiv"))
          if (this.checkIsExists(By.XPath(xpath2)))
          {
            this.driver.FindElement(By.XPath(xpath2)).Click();
            Thread.Sleep(this.wait_sec);
            //# 加入购物车
            if (this.checkIsExists(By.ClassName("add-to-cart")))
            {
              this.driver.FindElement(By.ClassName("add-to-cart")).Click();
              LogHelper.put("加入购物车成功,商品item-id:" + item_id);
              break;
            }
            else
            {
              LogHelper.put("未找到加入购物车按钮");
            }
          }
          else
          {
            LogHelper.put("没有查询到,可能是商品编码不对,或者已下架");
          }
          Thread.Sleep(this.wait_sec);
        }
        catch (Exception e)
        {
          Thread.Sleep(this.wait_sec);
          LogHelper.put(e);
        }
      }
    }

    /// <summary>
    /// 判断是否存在
    /// </summary>
    /// <param name="by"></param>
    /// <returns></returns>
    private bool checkIsExists(By by)
    {
      try
      {
        int i = 0;
        while (this.running && i < 3)
        {
          if (this.driver.FindElements(by).Count > 0)
          {
            break;
          }
          else
          {
            Thread.Sleep(this.wait_sec);
            i = i + 1;
          }
        }
        return this.driver.FindElements(by).Count > 0;
      }
      catch (Exception e)
      {
        LogHelper.put(e);
        return false;
      }
    }

  }
}

关于日志帮助类,代码如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using log4net;

[assembly: log4net.Config.XmlConfigurator(Watch = true)]
namespace AiSmoking.Core
{
  /// <summary>
  /// 日志帮助类
  /// </summary>
  public static class LogHelper
  {
    /// <summary>
    /// 日志实例
    /// </summary>
    private static ILog logInstance = LogManager.GetLogger("smoking");

    private static Queue<string> queue = new Queue<string>(2000);

    public static void put(string msg)
    {
      queue.Enqueue(msg);
      WriteLog(msg, LogLevel.Info);
    }

    public static void put(Exception ex)
    {
      WriteLog(ex.StackTrace, LogLevel.Error);
    }

    public static string get()
    {
      if (queue.Count > 0)
      {
        return queue.Dequeue();
      }
      else
      {
        return string.Empty;
      }
    }

    public static void WriteLog(string message, LogLevel level)
    {
      switch (level)
      {
        case LogLevel.Debug:
          logInstance.Debug(message);
          break;
        case LogLevel.Error:
          logInstance.Error(message);
          break;
        case LogLevel.Fatal:
          logInstance.Fatal(message);
          break;
        case LogLevel.Info:
          logInstance.Info(message);
          break;
        case LogLevel.Warn:
          logInstance.Warn(message);
          break;
        default:
          logInstance.Info(message);
          break;
      }
    }


  }


  public enum LogLevel
  {
    Debug = 0,
    Error = 1,
    Fatal = 2,
    Info = 3,
    Warn = 4
  }
}

作者:Alan.hsiang
出处:http://www.cnblogs.com/hsiang/

以上就是C# 利用Selenium实现浏览器自动化操作的示例代码的详细内容,更多关于c# 实现浏览器自动化操作的资料请关注其它相关文章!

您可能感兴趣的文章:
  • 用C#+Selenium+ChromeDriver爬取网页(模拟真实的用户浏览行为)
  • c# Selenium爬取数据时防止webdriver封爬虫的方法
  • c# 从内存中释放Selenium chromedriver.exe
  • C#使用Selenium的实现代码
  • C#使用Selenium+PhantomJS抓取数据
  • C#使用selenium实现爬虫

cucumber; Selenium WebDriver-如何使用Google Chrome浏览器代替Firefox作为测试浏览器

cucumber; Selenium WebDriver-如何使用Google Chrome浏览器代替Firefox作为测试浏览器

对于我的Rails 3.1应用程序上的Cucumber场景,我使用了@javascript标记,因此Selenium已激活。我收到以下错误:

Could not find Firefox binary (os=macosx). Make sure Firefox is installed or set the path manually with Selenium::WebDriver::Firefox::Binary.path= (Selenium::WebDriver::Error::WebDriverError)

如果可能的话,我想使用Google Chrome浏览器作为浏览器-而不是Firefox(我尚未安装)。这可能吗?该怎么办?

实际上,Cucumber / Selenium不应检测并使用浏览器吗?

====编辑====

添加后

Capybara.register_driver :selenium do |app|  Capybara::Selenium::Driver.new(app, :browser => :chrome)end

…到features / support / env.rb,我现在收到此错误:

Unable to find the chromedriver executable. Please download the server from http://code.google.com/p/chromium/downloads/list and place it somewhere on your PATH. More info at http://code.google.com/p/selenium/wiki/ChromeDriver. (Selenium::WebDriver::Error::WebDriverError)  ./features/step_definitions/web_steps.rb:45:in `/^(?:|I )am on (.+)$/''  features/update_memories.feature:11:in `Given I am on the home page''

我是从这里下载的,并且尝试将chromedriver可执行文件放在/
usr / bin中,但是仍然出现上述错误。

====编辑2 ====

进一步执行以下步骤并运行“ sudo chmod + x / usr / bin / chromedriver”后,在运行黄瓜之后,我现在收到一个新错误:

@javascript  Scenario: navigate to memory update page from home page              # features/update_memories.feature:11    Given I am on the home page                                        # features/step_definitions/web_steps.rb:44      unable to connect to chromedriver http://127.0.0.1:57870 (Selenium::WebDriver::Error::WebDriverError)      ./features/step_definitions/web_steps.rb:45:in `/^(?:|I )am on (.+)$/''      features/update_memories.feature:12:in `Given I am on the home page''    When I activate the edit memory switch for the memory "I played"   # features/step_definitions/memories/memory_steps.rb:5    Then I should be on the edit memory page for the memory "I played" # features/step_definitions/web_steps.rb:187      PGError: server closed the connection unexpectedly        This probably means the server terminated abnormally        before or while processing the request.      : ROLLBACK (ActiveRecord::StatementInvalid)

帮助赞赏!越来越近…

答案1

小编典典

对于水豚,将其添加到 env.rb

Capybara.register_driver :selenium do |app|  Capybara::Selenium::Driver.new(app, :browser => :chrome)end

下载Chrome驱动程序可执行文件并将其复制到您的路径中,例如
/ usr / bin / 并使其可执行

$ sudo chmod +x /usr/bin/chromedriver

Firefox更新后无法使用Selenium打开浏览器

Firefox更新后无法使用Selenium打开浏览器

如何解决Firefox更新后无法使用Selenium打开浏览器?

:目前的解决方案是降级Firefox!运行此命令以获取可用Firefox版本的列表。

apt-cache show firefox | grep Version

我的结果:

Version: 47.0+build3-0ubuntu0.16.04.1
Version: 45.0.2+build1-0ubuntu1

安装:

sudo apt-get install firefox=45.0.2+build1-0ubuntu1

要保留此版本并禁止更新:

sudo apt-mark hold firefox

如果要取消保留Firefox版本并允许更新:

sudo apt-mark unhold firefox
sudo apt-get upgrade

解决方法

我在Ubuntu Desktop 16.04上使用Selenium
WebDriver,但无法打开浏览器。Firefox更新后出现以下错误(在此之前,所有方法都可以正常工作):

Traceback (most recent call last):
  File "test.py",line 6,in <module>
    driver = webdriver.Firefox()
  File "/usr/local/lib/python3.5/dist-packages/selenium/webdriver/firefox/webdriver.py",line 81,in __init__
    self.binary,timeout)
  File "/usr/local/lib/python3.5/dist-packages/selenium/webdriver/firefox/extension_connection.py",line 51,in __init__
    self.binary.launch_browser(self.profile,timeout=timeout)
  File "/usr/local/lib/python3.5/dist-packages/selenium/webdriver/firefox/firefox_binary.py",line 68,in launch_browser
    self._wait_until_connectable(timeout=timeout)
  File "/usr/local/lib/python3.5/dist-packages/selenium/webdriver/firefox/firefox_binary.py",line 98,in _wait_until_connectable
    raise WebDriverException("The browser appears to have exited "
selenium.common.exceptions.WebDriverException: Message: The browser appears to have exited before we could connect. If you specified a log_file in the FirefoxBinary constructor,check it for details.

我们今天的关于由于“此浏览器或应用可能不安全,”无法使用Selenium自动化登录google。的分享就到这里,谢谢您的阅读,如果想了解更多关于C# 利用Selenium实现浏览器自动化操作、C# 利用Selenium实现浏览器自动化操作的示例代码、cucumber; Selenium WebDriver-如何使用Google Chrome浏览器代替Firefox作为测试浏览器、Firefox更新后无法使用Selenium打开浏览器的相关信息,可以在本站进行搜索。

本文标签: