首页 > 解决方案 > Python打印前三行文本

问题描述

import requests
from bs4 import BeautifulSoup
import csv


url = "https://alta.ge/phones-and-communications/smartphones.html"
r = requests.get(url)
content = r.text

soup = BeautifulSoup(content, 'html.parser')

a = soup.find_all('div', {'class':'ty-grid-list__item-name'})
for smartphone in a:
    a = smartphone.find('a').get_text()
    print(a)

这是我运行时的代码,它会打印每个项目的名称。我只想打印前 3 个项目,我该怎么做?

标签: pythonhtmlweb-scrapingbeautifulsoup

解决方案


而不是使用

for smartphone in a:
    a = smartphone.find('a').get_text()
    print(a)

您可以尝试将其替换为:

for smartphone in a:
    if count < 3:
        a = smartphone.find('a').get_text()
        print(a)
        count += 1

推荐阅读