【问题标题】:Selenium: Iterating through groups of elementsSelenium:遍历元素组
【发布时间】:2015-01-16 08:56:08
【问题描述】:

我已经用 BeautifulSoup 完成了这个,但它有点麻烦,我正在尝试弄清楚我是否可以直接用 Selenium 来完成。

假设我有以下 HTML,它在页面源中重复多次,元素相同但内容不同:

<div class="person">
    <div class="title">
        <a href="http://www.url.com/johnsmith/">John Smith</a>
    </div>
    <div class="company">
        <a href="http://www.url.com/company/">SalesForce</a>
    </div>
</div>

我需要构建一个字典,其中每个人的条目如下所示:

dict = {'name' : 'John Smith', 'company' : 'SalesForce'}

我可以通过以下方式轻松让 Selenium 生成每个顶级元素的内容列表:

driver.find_elements_by_class_name('person')

但是我无法遍历列表,因为上述方法不会将范围/源缩小到该元素的内容。

如果我尝试做这样的事情:

people = driver.find_elements_by_class_name('person')
for person in people:
    print person.find_element_by_xpath['//div[@class="title"]//a').text

我只是一遍又一遍地得到相同的名字。

我需要按组进行此操作,因为在我的情况下,遍历整个页面并单独附加每个标签是行不通的(有无限滚动,因此效率非常低)。

有谁知道是否可以直接在 Selenium 中执行此操作,如果可以,如何操作?

【问题讨论】:

    标签: python html selenium beautifulsoup html-parsing


    【解决方案1】:

    使用find_elements_by_class_name() 获取所有块,使用find_element_by_xpath() 获取每个人的titlecompany

    persons = []
    for person in driver.find_elements_by_class_name('person'):
        title = person.find_element_by_xpath('.//div[@class="title"]/a').text
        company = person.find_element_by_xpath('.//div[@class="company"]/a').text
    
        persons.append({'title': title, 'company': company})
    

    【讨论】:

    • 这很有意义,但它不起作用。请在我的 OP 中查看更新的示例代码,我相信它与您发布的相同。它一遍又一遍地返回相同的名称(我从列表中的第一个对象猜测)。似乎并没有缩小范围...
    • @AutomaticStatic 我在发布后简短地更新了答案。出现错误(在循环中使用 driver 而不是 person)。请再检查一次。谢谢。
    • 我正在做你写的事情(除了使用 print 语句检查它返回的内容)并且它仍然一遍又一遍地返回相同的名称。
    • 是 .// 而不是 // 表示它是一个孩子?对不起,如果这是一个愚蠢的问题。我正在慢慢熟悉 xpath 表示法。
    • @AutomaticStatic 是的,点是这里的关键,我们说引擎在元素的范围内搜索。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-03-09
    • 1970-01-01
    • 1970-01-01
    • 2019-05-15
    • 1970-01-01
    • 1970-01-01
    • 2012-12-03
    相关资源
    最近更新 更多