python selenium从元素获取文本

2024-09-29 19:29:36 发布

您现在位置:Python中文网/ 问答频道 /正文

如何从这个HTML树中提取文本“英超联赛(英语1)”?(标记部分) enter image description here

我用xpath、css选择器、类获取文本。。。但我似乎无法提取此文本

基本上,我想创建一个列表,检查所有包含文本(联盟)的“class=with icon”元素,并将文本附加到该列表中

这是我最后一次尝试:

def scrape_test():
    alleligen = []

    #click the dropdown menue to open the folder with all the leagues
    league_dropdown_menue = driver.find_element_by_xpath('/html/body/main/section/section/div[2]/div/div[2]/div/div[1]/div[1]/div[7]/div')
    liga_dropdown_menue.click()
    time.sleep(1)
    
    #get text form all elements that conain a league as text
    leagues = driver.find_elements_by_css_selector('body > main > section > section > div.ut-navigation-container-view--content > div > div.ut-pinned-list-container.ut-content-container > div > div.ut-pinned-list > div.ut-item-search-view > div.inline-list-select.ut-search-filter-control.has-default.has-image.is-open.active > div > ul > li:nth-child(3)')
    
    #append to list
    alleligen.append(leagues)
    
    print(alleligen)

但是我没有得到任何输出

我错过了什么

(我不熟悉编码)


Tags: the文本div列表containerwithsectioncss
3条回答

试试这个

path = "//ul[@class='inline-list']//li[first()+1]"
element = WebDriverWait(driver, 5).until(EC.presence_of_element_located((By.XPATH, path))).text

print(element)

path指定要作为目标的元素。路径中的第一个//表示要查找的元素不是页面中的第一个元素,而是存在于页面中的某个位置li[first()+1]表示您对第一个li后面的li标记感兴趣

WebDriverWait等待网页完全加载指定的秒数(在本例中为5秒)。您可能希望将WebdriverWait放在try块中

最后的.text解析标记中的文本。在本例中,它是您想要的文本Premier League (ENG 1)

你能试试吗

leagues = driver.find_elements_by_xpath(“//li[@class=‘with-icon’ and contains(text(), ‘League’)]”)
For league in leagues:
     alleligen.append(league.text)
print(alleligen)

如果知道定位器将保持在该列表树中的同一位置,则可以使用以下选项,其中li元素是基于其索引获取的:

locator= "//ul[@class='inline-list']//li[2]"
element = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.XPATH, locator))).text

相关问题 更多 >

    热门问题