首页 > 解决方案 > Python Beautiful Soup 没有循环结果

问题描述

我第一次使用 BS4,需要将在线目录中的项目刮到 csv 中。我已经设置了我的代码,但是当我运行代码时,结果只会重复目录中的第一个项目 n 次(其中 n 是项目数)。有人可以查看我的代码并让我知道我哪里出错了。

谢谢

import requests
from bs4 import BeautifulSoup
from csv import writer


#response = requests.get('https://my.supplychain.nhs.uk/Catalogue/browse/27/anaesthetic-oxygen-and-resuscitation?CoreListRequest=BrowseCoreList')
response = requests.get('https://my.supplychain.nhs.uk/Catalogue/browse/32/nhs-cat?LastCartId=&LastFavouriteId=&CoreListRequest=BrowseAll')

soup = BeautifulSoup(response.text , 'html.parser')
items = soup.find_all(class_='productPrevDetails')
#print(items)
for item in items:
    ItemCode = soup.find(class_='product_npc ').get_text().replace('\n','')
    ItemNameS = soup.select('p')[58].get_text()    
    ProductInfo = soup.find(class_='product_key_info').get_text()

    print(ItemCode,ItemNameS,ProductInfo)

标签: pythonloopsbeautifulsoup

解决方案


您总是看到第一个结果,因为您正在搜索soup,而不是item. 尝试

for item in items:
    ItemCode = item.find(class_='product_npc ').get_text().replace('\n','')
    ItemNameS = item.select('p')[58].get_text()    
    ProductInfo = item.find(class_='product_key_info').get_text()

    print(ItemCode,ItemNameS,ProductInfo)

推荐阅读