检查列表中是否有下一项以避免:列表索引超出范围
Check if there is a next item on the list to avoid: list index out of range
我正在寻找解决方案
I try to get the images from:
<pics>
<pic>240006.jpg</pic>
<pic>240006_2.jpg</pic>
</pics>
欢迎使用此代码:
for x in root.iter('product'):
pics =x.findall('pics/pic')
images = "https://cdn.edc-internet.nl/800/" + pics[0].text + ";" + "https://cdn.edc-internet.nl/800/" + pics[1].text + ";" + "https://cdn.edc-internet.nl/800/" + pics[2].text
print(images)
有些产品有 2 张图片,它创建了一个“列表超出范围”
我想检查是否有值,如果没有让在线查看 2 甚至 1 张图像 link。
我已经用 if 语句尝试过但失败了,我已经尝试过:但这只给我 3 张图片的价值
试试这个:
for x in root.iter('product'):
pics=x.findall('pics/pic')
for i in range(len(pics)):
images=images+"https://cdn.edc-internet.nl/800/"+pics[i].text+";"
print(images)
由于您可能不知道 pics
中有多少元素,更好的方法是对其进行迭代,即时创建 URL。这将避免使用固定索引,如您所见,如果 pics
长度小于 3,则可能会中断,如果最终抓取的长度超过 3,则 return 所有项目。
for x in root.iter('product'):
pics = x.findall('pics/pic')
URL = "https://cdn.edc-internet.nl/800/%s"
images = ";".join(URL % picture for picture in pics)
print(images)
我正在寻找解决方案
I try to get the images from:
<pics>
<pic>240006.jpg</pic>
<pic>240006_2.jpg</pic>
</pics>
欢迎使用此代码:
for x in root.iter('product'):
pics =x.findall('pics/pic')
images = "https://cdn.edc-internet.nl/800/" + pics[0].text + ";" + "https://cdn.edc-internet.nl/800/" + pics[1].text + ";" + "https://cdn.edc-internet.nl/800/" + pics[2].text
print(images)
有些产品有 2 张图片,它创建了一个“列表超出范围” 我想检查是否有值,如果没有让在线查看 2 甚至 1 张图像 link。
我已经用 if 语句尝试过但失败了,我已经尝试过:但这只给我 3 张图片的价值
试试这个:
for x in root.iter('product'):
pics=x.findall('pics/pic')
for i in range(len(pics)):
images=images+"https://cdn.edc-internet.nl/800/"+pics[i].text+";"
print(images)
由于您可能不知道 pics
中有多少元素,更好的方法是对其进行迭代,即时创建 URL。这将避免使用固定索引,如您所见,如果 pics
长度小于 3,则可能会中断,如果最终抓取的长度超过 3,则 return 所有项目。
for x in root.iter('product'):
pics = x.findall('pics/pic')
URL = "https://cdn.edc-internet.nl/800/%s"
images = ";".join(URL % picture for picture in pics)
print(images)