首页 \ 问答 \ 如何使用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

相关文章

更多

最新问答

更多
  • 如何避免MDIParent表单调整大小(How do I avoid MDIParent form from resizing)
  • Angular自定义指令调用另一个自定义指令(Angular custom directive calling another custom directive)
  • 如何通过参数将文本解析并附加到SQL Server 2005中的存储过程(How to Parse and Append text to a stored procedure in SQL Server 2005 via a parameter)
  • OpenCV中心Homography(OpenCV Center Homography)
  • 如何在linux shell脚本中计算日期-N?(How to calculate date -N in linux shell scripting?)
  • 如何使用Devise创建用户配置文件?(How Do I Create a User Profile With Devise?)
  • 清理模式以管理树上的多步异步过程(Clean pattern to manage multi-step async processes on a tree)
  • 场景的角色(Role of the Scene)
  • 组件中的Angular 2组件[重复](Angular 2 Component In Component [duplicate])
  • jsPlumb draggable element javascript函数(jsPlumb draggable element javascript function)
  • MVC4:ViewModel(带有radiobuttonlist)在HttpPost之后为空(MVC4: ViewModel (with radiobuttonlist) is empty after HttpPost)
  • 如何在同一帐户上设置“Dev repo”(在prod和团队之间)(How to set up a “Dev repo” (between the prod and the team) on the same account)
  • 如何在tcl中将eth0配置为发送方udp端口(how to configure eth0 as a sender udp port in tcl)
  • 如何使用预定义文本替换来自数据库的部分结果(How do I replace part of result coming from Database with predefined text)
  • Selenium Java注入了新的Javascript函数(Selenium Java inject new Javascript function)
  • 使用.on的多个下拉菜单选择文本仅适用于第一个下拉列表(Multiple Dropdowns Menu Selection text using .on works only on first dropdown)
  • 快速将黄土曲线添加到大型数据集图中的方法(Quick way to add loess curve to large data set graph)
  • FilteringSelect in mvc(FilteringSelect in mvc)
  • 在Delphi XE2中开发Mac或iOS应用程序需要哪些硬件/软件?(What hardware/software is necessary to develop Mac or iOS apps in Delphi XE2?)
  • 在原型的构造函数中初始化属性时获取“未定义”(Getting 'undefined' when a property is initialized in the constructor of a prototype)
  • 通过越狱加载的应用程序的Documents文件夹位置(Location of Documents folder for an app loaded via jailbreak)
  • 在OpenGL中使用可编程和固定管道功能(Using both programmable and fixed pipeline functionality in OpenGL)
  • 将任何用户输入重定向到单独的底层程序(redirect any user input to a separate underlying program)
  • 编辑文本不能正常工作android(Edit texts not working properly android)
  • “user_denied”Facebook应用页面上的Facebook用户区域设置(Facebook user locale on “user_denied” facebook app page)
  • 在大图像中找到小的部分透明图像的坐标(find coordinates of small partially-transparent image within a large image)
  • 我如何在cakephp 3.1中获得完整的相对路径?(How i can get full relative path of image in cakephp 3.1?)
  • 如何保存拖动标记的新本地化?(How to save new localization of dragged marker?)
  • MySQL UPDATE vs INSERT和DELETE(MySQL UPDATE vs INSERT and DELETE)
  • 在执行查询之前,在SQLAlchemy模型中将datetime转换为unix时间戳?(Convert datetime to unix timestamp in SQLAlchemy model before executing query?)