这里完全是菜鸟。我在网上搜索过,找不到我想要做的事情的答案。我的代码在这里:
import bs4 as bs
import urllib.request
sauce = urllib.request.urlopen('https://www.amazon.com/gp/rss/
bestsellers/kitchen/289851/ref=zg_bs_289851_rsslink').read()
soup = bs.BeautifulSoup(sauce,'lxml')
for title in soup.find_all('title'):
output = title.string
print(output)
给我这个输出:
Amazon.com: Best Sellers in Kitchen & Dining > Kitchen Knives & Cutlery
Accessories
#1: Kitchen Knife Sharpener - 3-Stage Knife Sharpening Tool Helps Repair,
Restore and Polish Blades - Cut-Resistant Glove Included (Black)
#2: KitchenIQ 50009 Edge Grip 2 Stage Knife Sharpener, Black
#3: Bavarian Edge Kitchen Knife Sharpener by BulbHead, Sharpens, Hones, &
Polishes Serrated, Beveled, Standard Blades
#4: PriorityChef Knife Sharpener for Straight and Serrated Knives, 2-Stage
Diamond Coated Wheel System, Sharpens Dull Knives Quickly, Safe and Easy to
Use
#5: MAIRICO Ultra Sharp Premium Heavy Duty Kitchen Shears and Multi Purpose
Scissors
#6: OXO Good Grips 3-in-1 Avocado Slicer, Green
#7: LINKYO Electric Knife Sharpener, Kitchen Knives Sharpening System
#8: BambooWorx Sushi Making Kit – Includes 2 Sushi Rolling Mats, Rice
Paddle, Rice Spreader |100% Bamboo Sushi Mats and Utensils.
#9: HOMWE Kitchen Cutting Board (3-Piece Set) | Juice Grooves w/ Easy-Grip
Handles | BPA-Free, Non-Porous, Dishwasher Safe | Multiple Sizes (Set of
Three, Gray)
#10: Ouddy 16 Inch Magnetic Knife Holder, Stainless Steel Magnetic Knife
Bar, Magnetic Knife Strip, Knife Rack Strip
我想做的是将每个项目编号保存到一个列表中,我可以调用...例如打印项目 1 或项目 2 或等等,它只会打印特定行。
提前非常感谢您的帮助。
当然,你可以通过将标题存储在 Python 列表中并使用其索引访问它们来实现。以下是如何操作:
import bs4 as bs
import urllib.request
sauce = urllib.request.urlopen('https://www.amazon.com/gp/rss/bestsellers/kitchen/289851/ref=zg_bs_289851_rsslink').read()
soup = bs.BeautifulSoup(sauce,'lxml')
# 创建一个空列表来存储标题
titles = []
for title in soup.find_all('title'):
titles.append(title.string)
# 现在 titles 列表包含所有标题,可以使用其索引访问它们
# 例如,要打印第一个标题:
print(titles[0])
# 要打印第二个标题:
print(titles[1])
# 你可以使用循环迭代所有标题并打印它们及其编号:
for i, title in enumerate(titles):
print(f"#{i+1}: {title}")
这段代码首先创建一个列表
titles
。然后,它迭代所有找到的
title
标签,并将每个标题的
.string
值(这是实际的文本内容)追加到
titles
列表中。
现在,可以通过其索引访问列表中的每个标题。请记住,Python 列表的索引从 0 开始,因此第一个标题的索引为 0,第二个标题的索引为 1,依此类推。
该代码还演示了如何使用
enumerate()
函数来获取每个标题及其在列表中的索引,这在希望一起打印标题及其编号时非常有用。