首页 > 解决方案 > 尝试在使用 for 循环收集文本时将 WebElements 中的文本打印到同一行?

问题描述

在我的 for 循环中单独prints正确打印我想要的项目,但我很难将它们一起打印在同一行上。


#Grabbing text from the first column in the table that contains "Elephant"

for cell in driver.find_elements_by_xpath("//*[contains(text(),'Elephant')]"):
    ElepantText = cell.text
    print(ElephantText)

#This prints:
#Elephant 1
#Elephant 2
#Elephant 3 etc...which is what I want

for element in driver.find_elements_by_xpath("//[contains(text(),'Elephant')]/following::td[1]/span/select[1]"):
    selected = Select(element).first_selected_option
    select_text = selected.text
    print(select_text)


#This acquires the selected option in the dropdown menu following the cell that contains "Elephant" and prints the selected option which is what I want.

我试过了:

print(ElephantText, select_text)

但这只是返回 ElephantText 中的最后一个值,并且没有任何 select_text 选择的选项。

我还尝试使用以下方法将两者压缩在一起:

zipped = zip(ElephantText, select_text)
print(zipped)

但它返回这个:

<zip object at 'random hexadecimal number'>

我尝试再次将这些变成列表,但它只是将结果中的每个字母变成了列表中的一个项目,所以我现在有点没有想法。任何方向将不胜感激。

编辑

这就是我希望我的结果看起来的样子:

大象 1 - 已选

大象 2 - 已选

大象 3 - 已选

标签: pythonselenium

解决方案


ElephantText and selected_text are strings. You cannot zip them. You need to store all the text values (if you're iterating over the collections one after the other) and then zip the list of text values:

ElephantTexts = []

for cell in driver.find_elements_by_xpath("//*[contains(text(),'Elephant')]"):
    ElephantText = cell.text
    print(ElephantText)
    ElephantTexts.append(EelephantText)


Selected_texts = []

for element in driver.find_elements_by_xpath("//[contains(text(),'Elephant')]/following::td[1]/span/select[1]"):
    selected = Select(element).first_selected_option
    select_text = selected.text
    print(select_text)
    Selected_texts.append(selected_text)

merged = tuple(zip(ElephantTexts, Selected_texts))    # assuming they are the same size
for tup in merged:
    print(tup)

I ran the following code with hardcoded lists:

ElephantTexts = ['Elephant1', 'Elephant2', 'Elephant3']
Selected_texts = ['Selected1', 'Selected2', 'Selected3']
merged = tuple(zip(ElephantTexts, Selected_texts))    # assuming they are the same size
for tup in merged:
    print(tup)

and this is the output:

('Elephant1', 'Selected1')
('Elephant2', 'Selected2')
('Elephant3', 'Selected3')

推荐阅读