简体   繁体   中英

How to click on a search engine result if it matches the searched value

I'm new to selenium. I'm taking user input and based on that, I'm searching it in duckduckgo. I want, if the input value matches the search result weblink, the code should click on that matched website. My code executes successfully but it doesn't click on the weblink. This is my code:-

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.common.exceptions import NoSuchElementException, StaleElementReferenceException

stuff = input()
options = webdriver.ChromeOptions()
options.headless = True
options.add_argument("==lang=es")
browser = webdriver.Chrome()
browser.implicitly_wait(30)
browser.maximize_window()

browser.get('http://www.duckduckgo.com')
elem = browser.find_element_by_name('q')
elem.clear()

elem.send_keys(stuff)
elem.submit()

list = stuff.lower().replace(' ', '').split(',')
for a in browser.find_elements_by_id('links'):
    b = a.find_elements_by_tag_name('a')
    for link in b:
        url = link.get_attribute('href')
        if any(dom in url for dom in list):
            link.click()
        break

For eg; I enter this input value - Mitchell Centre, Darwin CBD, 0800 and my code runs and opens duckduckgo and enters this value in the search bar, it should click on the website which matches my input value (in the blue bubble), but the code stops after this.

在此处输入图像描述

I don't understand what the problem is, would be great if you guys could help me.

Actually I am from Java background but still if you could convert my two lines of java code into python you would be able achieve it

Your code:

for link in b: url = link.get_attribute('href') if any(dom in url for dom in list): link.click() break

Instead of link.get_attribute, Convert the above code as below

In Java we have.getText() method to get the Text.

So try to get the text which your looking for using python as below(I used Java)

link.getText() store this in a variable

For ex as in Java : String str = link.getText()

And then here comes your if Condition

use your contains method as in python the below one is in Java

if(str.contains("Mitchell Centre, Darwin CBD, 0800"))

link.click()
break

This code is working fine for me.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM