【问题标题】:Python to print first three lines of textPython打印前三行文本
【发布时间】:2020-11-17 11:57:26
【问题描述】:
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 个项目,我该怎么做?
【问题讨论】:
标签:
python
html
web-scraping
beautifulsoup
【解决方案1】:
而不是使用
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
【解决方案2】:
您可以尝试使用这些代码:
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[:3]:
a = smartphone.find('a').get_text()
print(a)
【解决方案3】:
您可以替换这部分代码:
for smartphone in a:
a = smartphone.find('a').get_text()
print(a)
有了这个:
count = 0
for smartphone in a:
if count < 3:
a = smartphone.find('a').get_text()
print(a)
count += 1
【解决方案4】:
你可以替换
for smartphone in a:
与
for smartphone in a[:3]:
仅循环遍历列表中的 3 个元素