【问题标题】: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 个项目,我该怎么做?

【问题讨论】:

  • 一个简单的 for 循环将是解决问题的一种方法。

标签: 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 个元素

        【讨论】:

          猜你喜欢
          • 2011-06-27
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-07-07
          • 2015-02-04
          • 1970-01-01
          • 1970-01-01
          • 2017-12-29
          相关资源
          最近更新 更多