首页 > 解决方案 > 抓取可点击的链接或 xpath

问题描述

我在网络应用程序中有这个 html 树: 在此处输入图像描述

我已经刮掉了所有联赛名称的所有文字。

但是我还需要一个 XPATH 或任何指示器,以便我可以告诉 selenium:如果我在我的 GUI 中从下拉菜单中选择例如 EFL League 2 (ENG 4),然后使用相应的 xpath 在网络应用程序。

我不知道如何从该树中提取 XPATCH 或任何其他可用于我的场景的解决方案。

知道如何解决这个问题吗?

如果我尝试提取“href”,它只会打印“无”

到目前为止,这是我的代码:

def scrape_test():

    leagues = []
    #click the dropdown menue to open the folder with all the leagues
    league_dropdown_menu = driver.find_element_by_xpath('/html/body/main/section/section/div[2]/div/div[2]/div/div[1]/div[1]/div[7]/div')
    league_dropdown_menu.click()
    time.sleep(1)
    
#get all league names as text
    scrape_leagues = driver.find_elements_by_xpath("//li[@class='with-icon' and contains(text(), '')]")
    for league in scrape_leagues:
        leagues.append(league.text)
    print('\n')

# HERE I NEED HELP! - I try to get a link/xpath for each corresponding league to use later with selenium
    scrape_leagues_xpath = driver.find_elements_by_xpath("//li[@class='with-icon']")
    for xpath in scrape_leagues_xpath:
        leagues.append(xpath.get_attribute('xpath')) #neither xpath, text, href is working here

    print(leagues)

标签: pythonseleniumxpathweb-scrapinglinked-list

解决方案


li节点没有text,hrefxpath(我认为它不是有效的 HTML 属性)。您可以抓取和解析@style.

尝试使用这种方法来提取背景图像 URL

leagues.append(xpath.get_attribute('style').strip('background-image:url("').rstrip('");'))

推荐阅读