首页 > 解决方案 > 如果在 try 块中找不到一个不同的 XPATH,如何尝试不同的 XPATH,Selenium Python

问题描述

我正在尝试找到指向不同链接的链接。但是它可以每次用一个数字改变,/html/body/div[4]/div/div[2]/div[5]/div[3]/div[7]/div[5]/span/a并且/html/body/div[4]/div/div[2]/div[5]/div[3]/div[7]/div[6]/span/a

但根据用户输入的内容,可能会有更多变化。

user_input = input("What movie would you like to filter:")
user_filter_type = input("What would you like to know \nChoose from list shown:\nnudity,\nviolence,\nprofanity,\ndrugs,\nhorror:")
user_filter_type.lower()


driver = webdriver.Chrome(PATH)  #, options=options)
driver.get('https://www.imdb.com/')

try:
    imdb_search = WebDriverWait(driver, 10).until(
        EC.presence_of_element_located((By.XPATH, "/html/body/div[2]/nav/div[2]/div[1]/form/div[2]/div/input"))
    )
    imdb_search.send_keys(user_input)
    imdb_search.send_keys(Keys.RETURN)
except:
    driver.quit()

try:
    first_result = WebDriverWait(driver, 10).until(
        EC.presence_of_element_located((By.XPATH, "/html/body/div[3]/div/div[2]/div[3]/div[1]/div/div[2]/table/tbody/tr[1]/td[2]/a"))
    )
    first_result.click()
except:
    driver.quit()

try:
    parent_guide_link = WebDriverWait(driver, 10).until(
        EC.presence_of_element_located((By.XPATH, "/html/body/div[4]/div/div[2]/div[5]/div[3]/div[7]/div[6]/span/a")) # I need another XPATH if this doesn't work.
    )
    parent_guide_link.click()
except:
    driver.quit()

xpath_for_filter_type = ""

if user_filter_type == "nudity":
    xpath_for_filter_type = "/html/body/div[3]/div/div[2]/div[3]/div[1]/section/section[2]"
elif user_filter_type == "violence":
    xpath_for_filter_type = "/html/body/div[3]/div/div[2]/div[3]/div[1]/section/section[3]"
elif user_filter_type == "profanity":
    xpath_for_filter_type = "/html/body/div[3]/div/div[2]/div[3]/div[1]/section/section[4]"
elif user_filter_type == "drugs":
    xpath_for_filter_type = "/html/body/div[3]/div/div[2]/div[3]/div[1]/section/section[5]"
elif user_filter_type == "horror":
    xpath_for_filter_type = "/html/body/div[3]/div/div[2]/div[3]/div[1]/section/section[6]"
else:
    print("Invalid choice. Please run program again ;)")



try:
    all_content = WebDriverWait(driver, 10).until(
        EC.presence_of_element_located((By.XPATH, xpath_for_filter_type))
    )
    print(all_content.text)
except:
driver.quit()

该代码应该获取用户想要观看的电影/节目,并获取他们试图阻止的过滤器类型,但是您可能知道,他们将输入不同的电影/节目,并且在找到父指南链接时电影/节目的 IMDB 页面,它可以更改。我该如何解决?

标签: pythonpython-3.xselenium

解决方案


在这种情况下,不要使用您从浏览器获得的 XPath,而是制作您自己的自定义 XPath。
您可以基于链接文本或其类或 id 或任何此类属性创建 XPath,无论位置如何,它们都保持不变。

我建议学习 XPath 的基础知识,因为从长远来看它也会对您有所帮助。

例如,在这种情况下,我会制作一个 XPath,例如, //a[contains(@href, 'violence') and contains(text(), 'Violence')]


推荐阅读