简体   繁体   English

Python打印前三行文本

[英]Python to print first three lines of text

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)

this is my code when i run it prints names of every item.这是我运行时的代码,它打印每个项目的名称。 i only want to print first 3 items, how do i do that?我只想打印前 3 个项目,我该怎么做?

Instead of using而不是使用

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

You can try to replace it with:您可以尝试将其替换为:

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

You could try using these codes:您可以尝试使用这些代码:

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)

You can replace this part of your code:您可以替换这部分代码:

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

With this:有了这个:

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

You can replace你可以更换

for smartphone in a:

with

for smartphone in a[:3]:

to loop trough 3 elements in list only仅循环遍历列表中的 3 个元素

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM