使用 Selenium Webdriver 在元素中查找元素 [英] Finding an element within an element using Selenium Webdriver

查看:56
本文介绍了使用 Selenium Webdriver 在元素中查找元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在抓取一个网站,其中包含使用 JavaScript 生成的足球比赛列表.我编写了以下行来创建页面上所有游戏元素的列表:

I am scraping a website that has a list of football games generated using JavaScript. I have written the following line that creates a list of all the game elements on the page:

list = browser.find_elements_by_xpath('//*[@data-sportid="1"]')

如果我写了

for game in list:
    print game.text

它会打印每场比赛中包含的所有文本字段(主队名称、客队名称等)

it prints all the text fields contained in each of the games (home team name, away team name, etc.)

然而,循环

for game in list:
    print game.find_element_by_xpath('//*[@class="home-team"]').text

为循环的每次迭代在页面中打印第一个主队的名称.

prints the very first home team's name in the page for each iteration of the loop.

看起来 game.find_element_by_xpath 正在搜索整个页面,而不仅仅是这个 game 元素,因此它不断返回页面上的第一个主队名称.

It appears that game.find_element_by_xpath is searching the entire page, and not just this game element, and so it keeps returning the first home team name on the page.

如何在列表的每个项目中搜索子元素?

How can I search for a child element within each item of the list?

编辑

这是我正在处理的确切页面

推荐答案

@Justin Bartz 谢谢.

@Justin Bartz Thank you.

您使用的是 XPath //*[@class="home-team"] 但无论您使用的是哪个父元素,// 都会告诉 XPath搜索整个文档而不仅仅是父元素的子元素.使用 XPath .//*[@class=home-team"] 和正斜杠(IE .//)前面的句点,它告诉它只在当前元素下搜索.

You were using XPath //*[@class="home-team"] but no matter what parent element you are using the // tells XPath to search the whole document not just the children of the parent element. Using the XPath .//*[@class="home-team"] with the period in front of the forward slashes (IE .//) it tells it to search under the current element only.

希望这个扩展的解释有助于理解.

Hope this expanded explanation helps the understanding.

   driver = webdriver.Chrome()
    driver.get("https://www.betfair.com/exchange/football/coupon?id=2")
    list = driver.find_elements_by_xpath('//*[@data-sportid="1"]')
    for game in list:
        print(game.find_element_by_css_selector('span.home-team').text)

or

    driver = webdriver.Chrome()
    driver.get("https://www.betfair.com/exchange/football/coupon?id=2")
    list = driver.find_elements_by_xpath('//*[@data-sportid="1"]')
    for game in list:
        print(game.find_element_by_xpath('.//span[@class="home-team"]').text)

这篇关于使用 Selenium Webdriver 在元素中查找元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆