python - 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)
解决方案
您总是看到第一个结果,因为您正在搜索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)
推荐阅读
- android - PreferenceHeaders 中图标的填充是否与 PreferenceScreens 不同?
- javascript - 输入类型颜色和 v-model 的 Vue 性能问题
- nginx - 如何调试未关闭的 CLOSE_WAIT 连接的原因?(tcpdump 等)
- spring-boot - Spring Cloud Stream Kafka 多重绑定
- mysql - 如何根据列的值对 Laravel 中的行进行排序?
- python - Python tkinter 如何使用网格粘性
- python-3.7 - icon_path 在 python 的 win10toast 模块中不起作用
- python - 如何仅翻译 DRF 中的自定义错误消息?
- lowpass-filter - 对正在进行的样本进行低通滤波器
- c - C程序:用链表改变队列的数据格式