python - 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 个项目,我该怎么做?
解决方案
而不是使用
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
推荐阅读
- swift - 从 Swift 中的字符串中删除 '
- python - Python:将开始日期和结束日期拆分为开始日期和结束日期之间的所有日期
- javascript - Rxjs 在继续之前等待先前的间隔请求执行
- python - Python中两个矩阵的并集
- smtp - Gerrit 无法发送电子邮件验证消息 504
- python - 将创建动态类的函数转换为 Python 中的动态包装类
- android - public final fun actionConformationFragmentToHomeFragment() 的参数太多
- java - NoClassDefFoundError: com/mongodb/MongoClientURI
- php - PHP Netbeans 断点仅在运行代码上
- scala - java.net.SocketException:从 Azure Databricks 调用 Azure Maps 服务时出现连接重置错误