python硒从元素获取文本

时间:2020-09-08 15:02:38

标签: python list selenium web-scraping text

如何从此HTML树中提取文本“总理联赛(ENG 1)”? (标记部分) enter image description here

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

基本上,我想创建一个列表并遍历所有包含文本(同盟)的“带有图标的class”元素,并将文本附加到该列表中。

这是我最后一次尝试:

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)

但是我没有任何输出。

我在这里想念什么?

(我是编码新手)

3 个答案:

答案 0 :(得分:2)

尝试

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)

答案 1 :(得分: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)

答案 2 :(得分:1)

如果您知道定位符将保留在该列表树中的相同位置,则可以在根据li的索引获取li元素时使用以下内容:

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