如何修改Python爬虫代码以仅打印10条爬取到的商品数据
修改后可仅输出10条结果的代码
你只需要对遍历的序列做切片取前10个元素即可,修改后的代码如下:
import requests from bs4 import BeautifulSoup webpage = requests.get("https://www.spinneyslebanon.com/catalogsearch/result/?q=pepsi") soup = BeautifulSoup(webpage.content, 'html.parser') title = soup.find_all('a', 'product-item-link') price = soup.find_all('span', class_='price') # 取前10组匹配的商品名称和价格遍历输出 for t, p in list(zip(title, price))[:10]: print("{:<60} {:<30}".format(t.get_text(strip=True), p.get_text(strip=True)))
其他可选实现方式
如果你不想将zip对象转成列表,也可以通过计数器控制输出条数:
import requests from bs4 import BeautifulSoup webpage = requests.get("https://www.spinneyslebanon.com/catalogsearch/result/?q=pepsi") soup = BeautifulSoup(webpage.content, 'html.parser') title = soup.find_all('a', 'product-item-link') price = soup.find_all('span', class_='price') count = 0 for t, p in zip(title, price): if count >= 10: break print("{:<60} {:<30}".format(t.get_text(strip=True), p.get_text(strip=True))) count += 1
内容的提问来源于stack exchange,提问作者armen kaymakmaian 4
相关产品推荐
相关产品推荐

