首页 > 解决方案 > 使用 Selenium 遍历 li 标记没有从列表的前两个元素中获取 .text

问题描述

我正在尝试遍历操作选项卡中https://game-rainbow6.ubi.com/en-us/uplay/player-statistics/dbd1cef3-d69d-4296-a235-ae8d7d70363f/multiplayer上的 li 标签(选择选项卡不会更改链接,抱歉)我进入选项卡没有问题,但是当我获得 li 标签并遍历它以获取我需要的所有四个 Web 元素(名称、播放时间、k/d、w /l) 它跳过列表中的前两个运算符。它打印其余的就好了。我尝试隐式等待以查看前两个是否加载速度不快,但这不起作用,然后我尝试了现在代码中的显式等待,但每次都会超时。我还尝试通过 xpath 查找元素。这是第一个操作员名称的完整 xpath

//*[@id="section"]/div/div/div[2]/div/div[1]/div/div/div/div/article[3]/div[1]/div/div/div/nav/ul/li[1]/div/div[1]/div[1]/div/div[1]/p

我试着做

.//div/div[1]/div[1]/div/div[1]/p 

在 for 循环中,因为我只需要每个元素的路径尾端,但它仍然跳过前两个运算符。

我创建了一个测试登录,以便人们可以正确查看 html:

email = UbiTest1337@gmail.com
pwd = Password1

def scrapeOperatorStats(self):
    #navigate to operator tab
    operator_tab = self.driver.find_element_by_xpath('//* [@id="section"]/div/div/div[2]/div/div[1]/div/div/div/div/article[1]/div[2]/div/div[1]/button')

    self.driver.execute_script("arguments[0].click();", operator_tab)
    #wait for operator stats elements to load
 WebDriverWait(self.driver,10).until(EC.text_to_be_present_in_element((By.XPATH, '//*[@id="section"]/div/div/div[2]/div/div[1]/div/div/div/div/article[3]/div[1]/div/div/div/nav/ul/li[1]/div/div[1]/div[1]/div/div[1]/p')))

    #Get the li tag that is a list of all operators and thier respective stats
    operator_list_set = self.driver.find_element_by_xpath('//*[@id="section"]/div/div/div[2]/div/div[1]/div/div/div/div/article[3]/div[1]/div/div/div/nav/ul')
    operators = operator_list_set.find_elements_by_tag_name('li')

    for operator in operators:
        operator_stats = operator.find_elements_by_tag_name('p')
        for stat in operator_stats:
            print(stat.text)

标签: python-3.xseleniumxpath

解决方案


我发现你可以使用 get_attribute('innerHTML') 它会得到所有的元素,你甚至不需要切换标签。

    #Get the li tag that is a list of all operators and thier respective stats
    operator_list_set = self.driver.find_element_by_xpath('//*[@id="section"]/div/div/div[2]/div/div[1]/div/div/div/div/article[3]/div[1]/div/div/div/nav/ul')
    operators = operator_list_set.find_elements_by_tag_name('li')

    for operator in operators:
        operator_stats = operator.find_elements_by_tag_name('p')
        for stat in operator_stats:
            print(stat.get_attribute('innerHTML'))

推荐阅读