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

試著忘記壹切 提交于 2020-04-30 06:49:26

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/61458687/how-to-click-on-a-search-engine-result-if-it-matches-the-searched-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!