How to use 'not start-with' attribute of xpath in selenium to skip certain websites in python

妖精的绣舞 提交于 2020-05-16 03:24:06

问题


I've written a code which asks the user for input and opens duckduckgo to search for the website related to that input value. In the search results, I want to open the website which doesn't start with the website mentioned by me in //a[not(starts-with(@href, 'website'))].This is my code:

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.action_chains import ActionChains
import time
import pyautogui
from selenium.common.exceptions import NoSuchElementException, StaleElementReferenceException

stuff = input()
options = webdriver.ChromeOptions()
options.headless = True
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()

matched_elements = browser.find_elements_by_xpath('//a[not(starts-with(@href, "https://it.wikipedia.org/"))]' or '//a[not(starts-with(@href, "https://www.facebook.com"))]')

if matched_elements:
    matched_elements[0].click()

Suppose if the user has entered this input:- Regina Pacis, Reggio nell'Emilia, 42124 and the search results are these:-

I want the code to skip over the wikipedia and facebook search results and click on the link highlighted in red. But instead of that, the code goes back to duckduckgo.

I know I can easily achieve the result by:-

match_elements = browser.find_elements_by_class_name('result__url__domain')
match_elements[2].click()

But the search results are dynamic which will change as per user input. I'd really appreciate if you guys could help me


回答1:


You can use:

dom_bl = ["wikipedia.org", "facebook.com"]
match_elements = browser.find_elements_by_class_name('result__url')
for link in match_elements:
    url = link.get_attribute("href")
    if any(dom in url for dom in dom_bl):
        continue
    link.click()
    break


来源:https://stackoverflow.com/questions/60989133/how-to-use-not-start-with-attribute-of-xpath-in-selenium-to-skip-certain-websi

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