首页 \ 问答 \ 如何使用selenium-webdriver单击Google搜索结果(How can i click Google search result with selenium-webdriver)

如何使用selenium-webdriver单击Google搜索结果(How can i click Google search result with selenium-webdriver)

我有以下任务的问题:

  1. 打开Goog​​le初始页面
  2. 在搜索表单中输入请求
  3. 选择url与某个给定网址匹配的结果(例如http://www.theguardian.com

目前我有这个脚本:

from selenium import webdriver
from selenium.webdriver.common.keys import Keys

driver = webdriver.Firefox()
driver.get("https://google.com/")

search_form = driver.find_element_by_xpath("/html/body/div/div[3]/form/div[2]/div[2]/div[1]/div[1]/div[3]/div/div[3]/div/input[1]")
search_form.send_keys("guardian")
search_form.send_keys(Keys.ENTER)

driver.find_element_by_xpath('//a[starts-with(@href,"http://www.theguardian.com")]').click()

它成功执行前2个子任务但在最后一行抛出异常时:

selenium.common.exceptions.NoSuchElementException: Message: Unable to locate element: {"method":"xpath","selector":"//a[starts-with(@href,\"http://www.theguardian.com\")]"}

我也有这个脚本只满足最后一个子任务:

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
q = "guardian"
browser = webdriver.Firefox()
body = browser.find_element_by_tag_name("body")
body.send_keys(Keys.CONTROL + 't')

browser.get("https://www.google.com/search?q=" + q + "&start=" + str(counter))
browser.find_element_by_xpath('//a[starts-with(@href,"http://www.theguardian.com")]').click()

我工作正常。 我的问题是为什么第一个脚本抛出异常,我怎么能修改它,所以它打开搜索结果第二个脚本呢?

更新:

正如Bart和Shubham在评论中提到的,问题在于我试图在页面上找到尚未加载的元素。 因此解决方案是使用'等待'。

Selenium-webdriver提供了两种类型的“等待” - 在文档中明确隐含

对于我的解决方案,我使用隐式等待 基本上,它告诉WebDriver等待一定的时间来找到一个元素,如果它不能立即可用。

为此,我只在脚本中添加了1行:

driver.implicitly_wait(5)

I have problem with following task:

  1. Open Google start page
  2. Type request in search form
  3. Choose result where url matches some given url(for example http://www.theguardian.com)

Currently i have this script:

from selenium import webdriver
from selenium.webdriver.common.keys import Keys

driver = webdriver.Firefox()
driver.get("https://google.com/")

search_form = driver.find_element_by_xpath("/html/body/div/div[3]/form/div[2]/div[2]/div[1]/div[1]/div[3]/div/div[3]/div/input[1]")
search_form.send_keys("guardian")
search_form.send_keys(Keys.ENTER)

driver.find_element_by_xpath('//a[starts-with(@href,"http://www.theguardian.com")]').click()

It succesfully executes first 2 subtasks but when on last line throws exception:

selenium.common.exceptions.NoSuchElementException: Message: Unable to locate element: {"method":"xpath","selector":"//a[starts-with(@href,\"http://www.theguardian.com\")]"}

Also i have this script which satisfies only last subtask:

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
q = "guardian"
browser = webdriver.Firefox()
body = browser.find_element_by_tag_name("body")
body.send_keys(Keys.CONTROL + 't')

browser.get("https://www.google.com/search?q=" + q + "&start=" + str(counter))
browser.find_element_by_xpath('//a[starts-with(@href,"http://www.theguardian.com")]').click()

I works OK. My question is why first script throws exception on how can i modify it so it opens search result as second script does?

UPDATE:

As Bart and Shubham mentioned in comments, problem was in that i was trying to find element on page that wasn't yet loaded. So solution is to use 'wait'.

Selenium-webdriver provides 2 types of 'wait' -- explicit and implicit more on that in documentation.

For my solution i used implicit wait. Basically, it's telling WebDriver to wait for certain amount of time to find an element if it's not immediately available.

For that i just added 1 line to script:

driver.implicitly_wait(5)

原文:https://stackoverflow.com/questions/35171043
更新时间:2019-07-05 02:22

最满意答案

你可以做下面的事......

试着从第一个位置等一下

代码在java中,但它与python非常相似/接近,从中获取引用

您可以在HTML DOM中每次检查元素是否存在时进行检查,以防止出现错误/错误的脚本。 如下: -

  if (driver.findElements(By.xpath('//a[starts-with(@href,"http://www.theguardian.com')).size() != 0) {  
            YOUR FIRST Working code  
            System.out.println("element exists");     
        }  
  else{
           Your second working code    
      }

希望它能帮到你:)


You can do something like below ...

Try to put some wait from first place

The code is in java but it is very similar/near to python, take a reference from it

You can check everytime that your element is present or not in your HTML DOM to prevent from error/failer of script. like below:-

  if (driver.findElements(By.xpath('//a[starts-with(@href,"http://www.theguardian.com')).size() != 0) {  
            YOUR FIRST Working code  
            System.out.println("element exists");     
        }  
  else{
           Your second working code    
      }

Hope it will help you :)

2016-02-03

相关问答

更多

单击带有selenium-webdriver的复选框(Click a checkbox with selenium-webdriver)

这是一个适用于Java的简单示例: driver.findElement(By.id("checkbox_id")).click(); 在Python中,它似乎是: driver.find_element_by_id("checkbox_id").click() Here is a simple example that works for me in Java: driver.findElement(By.id("checkbox_id")).click(); In Python, it ...

用于解析的Selenium-webdriver(Ruby)(Selenium-webdriver for parsing (Ruby))

页面的html不是很好 - 即没有好的标识符来关联数据。 例如,只有相对定位允许您将公司名称与地址相关联。 下面的解决方案假设文本的位置很脆弱,但是我能想到的最好。 require 'rubygems' require 'selenium-webdriver' driver = Selenium::WebDriver.for :firefox driver.navigate.to 'http://www.ypag.ru/cat/komp249/page0.html' # The table t ...

Selenium-webdriver(Java Script)等待元素消失(Selenium-webdriver (Java Script) wait for element to disappear)

没有在代码源中找到负面等待。 解决方案是实现自己的条件: var webdriver = require('selenium-webdriver'); var until = webdriver.until; var By = webdriver.By; until.elementIsNotPresent = function elementIsNotPresent(locator) { return new until.Condition('for no element to be loc ...

如何使用selenium获得总搜索结果计数(How to get the total search result counts using selenium)

用于获取总搜索结果计数的Webelment不正确。 正确的元素/标签是“h2”,id为“s-result-count” 下面的行应该给你搜索结果数量: String result = driver.findElement(By.id("s-result-count")).getText().split(" ")[2]; Webelment used to get total search result count is not correct. Correct element/tag is "h ...

无法为Selenium / WebDriver运行Java示例(Can't run Java example for Selenium / WebDriver)

像这样编译: javac -classpath selenium-server-standalone-2.20.0.jar Example.java 除非将Java文件放入org.openqa.selenium.example ,否则必须删除软件包说明符。 像这样运行编译的文件: java -cp .:selenium-server-standalone-2.20.0.jar Example 这将当前目录链接到类路径。 Compile like so: javac -classpath sel ...

Selenium Server的行为与WebDriver不同(Selenium Server does not behave similarly to WebDriver)

所以看起来我能够通过自己的方式获得部分解决方案。 显然只是启动selenium服务器独立jar是不够的。 以下让我更进一步。 在服务器系统上(将打开并与实际浏览器交互的远程系统): java -jar selenium-server-standalone-2.31.0.jar -role hub 然后在新的终端窗口(仍然是服务器系统): java -jar selenium-server-standalone-2.31.0.jar -role node http://localhost:4444 ...

右键单击selenium webdriver问题(Right click in selenium webdriver problems)

“无法解析符号驱动程序” - 检查是否已创建WebDriver的实例并且可以访问。 对于Actions类 - 导入org.openqa.selenium.interactions.Actions; 提供完整的代码以协助。 "Cannot resolve symbol driver" - Check have you created the instance of the WebDriver and is accessible. For Actions class - import org.open ...

如何使用selenium webdriver选择弹出的子菜单(How to select the submenu of the flyout using selenium webdriver)

检查actions类,你需要这样的东西: WebElement element = driver.findElement(By.Id("id")); Actions builder = new Actions(driver); Actions hover = builder.moveToElement(element); hover.build().perform(); Check the actions class, something like this you need: WebElem ...

相关文章

更多

最新问答

更多
  • Unity着色器错误;(Unity shader error; presumably in if statement)
  • 如何在Liferay portlet中设置Cookie?(How to set a Cookie in Liferay portlet?)
  • C#只读访问List <>或其他集合,或ToArray()魔术(C# readonly access to List<> or other collection, or ToArray() magic)
  • 如何使用Google Web工具包创建登录应用程序?(How to create a login application using Google web tool kit? [closed])
  • 如何使我的函数返回结果作为全局变量?(How to make my function return results as a global variable?)
  • 为什么我的网站需要“启用32位应用程序”?(Why does my website need “Enable 32-bit applications”?)
  • 红宝石数组具有相同的值(ruby array of hash with same value)
  • Android(在Scala中):StackOverflowError取决于何时启动线程?(Android (in Scala): StackOverflowError depends on when to start a thread?)
  • 适用于iOS应用的通用链接(Universal Links for iOS apps)
  • 创建并打开文件linux编程(create and open file linux programming)
  • Datepicker,第2个日期是从第1个日期开始的X天(Datepicker, 2nd date is X days from 1st date)
  • 背景大小过渡不起作用(Transition on background-size doesn't work)
  • 在React / Redux中的On Click函数中传递Prop(Passing a Prop in an On Click Function in React/Redux)
  • 关键字在代码中做了什么,是否有没有此关键字的替代方法?(what does the keyword this does in the code and are there any alternate methods without this keyword? [duplicate])
  • 反向设计FoxPro / dBsae数据库以创建EER模型(Reverse Engineer a FoxPro/dBsae database to create the EER model)
  • 在R中的变量中组合具有相同值的行(Combine rows that have same value in a variable in R [duplicate])
  • SQL Server:非空唯一主键(SQL Server: Non-null unique vs. Primary Key)
  • 将扩展ASCII字符代码转换为ISO-8859-1(Convert extended ASCII character codes to ISO-8859-1)
  • 如何在.NET中读取m4a文件中的标签?(How to read tags out of m4a files in .NET?)
  • 呼叫链接的性能提升?(Performance gain on call chaining?)
  • 风景名胜区规划设计文本里面都包含哪些内容?推荐一家旅游规划设计公司?谢谢!
  • 如何在String中将字符串转换为枚举?(How do I convert a string to enum in TypeScript?)
  • SQLite SELECT出现异常如何解决它?(SQLite SELECT gives exception How to fix it?)
  • NSLog不会从ViewController类输出,而是来自AppDelegate类的WILL。(NSLog will NOT output from the ViewController class, but WILL from the AppDelegate class. iOS:Objective C)
  • 更改UIPicker突出显示的标签宽度(change UIPicker highlighted tab width)
  • 空心倒五角形(Hollow inverted pentagon)
  • 如何设置仅使用OpenID的Plone站点(How to setup Plone sites working only with OpenID)
  • Paperclip缺少Amazon S3的协议(https)(Paperclip is missing the Protocol (https) with Amazon S3)
  • 从宏中部署netbeans中的ANT文件(Deploy ANT file in netbeans from macro)
  • XMLReader是未知的(XMLReader is unknown)