python - 尝试在使用 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 - 已选
解决方案
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')
推荐阅读
- flutter - 在颤振中将其添加到firebase身份验证后如何存储在Firestore数据库中
- azure - 具有 Azure 功能的 Azure 存储帐户上的 HTML 表单
- r - 如何用受特定条件限制的其他字段的最大值/最小值替换字段中的值?
- r - 根据另一列中的 ID 转置 R 中的列
- javascript - 如何合并此代码,我尝试了几种方法,但无法使其正常工作
- c# - ML.Net PredictionEnginePool 和多输入
- arrays - 将数组切片转换为切片数组
- vue.js - 中心饼图
- docker - 安装 Docker Desktop for Windows 时遇到问题
- vue.js - cybersource-rest-client 未找到这些依赖项(Vue.js)