首页 > 解决方案 > 如何在 python 中使用 selenium 在变量中添加具有相同类的所有元素

问题描述

content = driver.find_element_by_class_name('topics-sec-block')
container = content.find_elements_by_xpath('//div[@class="col-sm-7 topics-sec-item-cont"]')

代码如下:

for i in range(0, 40):
    title = []
    url = []
    heading=container[i].find_element_by_xpath('//div[@class="col-sm-7 topics-sec-item-cont"]/a/h2').text
    link = container[i].find_element_by_xpath('//div[@class="col-sm-7 topics-sec-item-cont"]/a')

    title.append(heading)
    url.append(link.get_attribute('href'))

    print(title)
    print(url)

它给了我 40 行,但所有行的标题和 url 都相同(其中一些在下面给出):

['Stuck in Mexico: Central American asylum seekers in limbo']
['https://www.aljazeera.com/news/2020/03/stuck-mexico-central-american-asylum-seekers-limbo-200305103910955.html']
['Stuck in Mexico: Central American asylum seekers in limbo']
['https://www.aljazeera.com/news/2020/03/stuck-mexico-central-american-asylum-seekers-limbo-200305103910955.html']

标签: python-3.xselenium-webdriver

解决方案


推荐阅读