Selenium:通过一组元素迭代

Aut*_*tic 13 html python selenium beautifulsoup html-parsing

我用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>
Run Code Online (Sandbox Code Playgroud)

我需要建立一个字典,每个人的条目看起来像:

dict = {'name' : 'John Smith', 'company' : 'SalesForce'}
Run Code Online (Sandbox Code Playgroud)

通过执行以下操作,我可以轻松地让Selenium生成每个顶级元素的内容列表:

driver.find_elements_by_class_name('person')
Run Code Online (Sandbox Code Playgroud)

但是后来我不能遍历列表,因为上面的方法不会将范围/源缩小到只是该元素的内容.

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

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

我一遍又一遍地得到同样的名字.

我需要按组进行分组,因为在我的情况下,遍历整个页面并单独附加每个标记将无效(存在无限滚动,因此效率非常低).

有谁知道是否有可能直接在Selenium中这样做,如果是这样的话怎么样?

ale*_*cxe 22

使用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})
Run Code Online (Sandbox Code Playgroud)

  • @AutomaticStatic是的,点是关键在这里,我们说的是引擎搜索元素的范围. (6认同)
  • 是//而不是//表示它是一个孩子?对不起,如果这是一个愚蠢的问题.我正逐渐熟悉xpath表示法. (3认同)