无法测量lis中每个项目的频率

2024-03-29 08:24:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我用python编写了一个脚本,可以从网页中提取不同项目的名称。我的剧本可以做得很好。有些物品不止一次出现。我想刮掉每件商品的外观编号。你知道吗

import requests
from bs4 import BeautifulSoup

baseUrl = 'https://www.etsy.com/shop/JpKrHk/sold?ref=pagination&page=2'

res = requests.get(baseUrl)
soup = BeautifulSoup(res.text,'lxml')
items = [item.get_text(strip=True) for item in soup.select(".v2-listing-card__info h2")]
print(len(items))

找出每个项目在列表中出现多少次的正确方法是什么?


Tags: 项目textimport脚本名称网页getitems
1条回答
网友
1楼 · 发布于 2024-03-29 08:24:22

除了使用注释中建议的Counter外,还可以使用dict理解和listcount()方法:

import requests
from bs4 import BeautifulSoup

baseUrl = 'https://www.etsy.com/shop/JpKrHk/sold?ref=pagination&page=2'

res = requests.get(baseUrl)
soup = BeautifulSoup(res.text,'lxml')
items = [item.get_text(strip=True) for item in soup.select(".v2-listing-card__info h2")]
items = {i:items.count(i) for i in items}
print(items)
>>> {'1612-Plain 08, 3 sheets Korean Cotton Sticker sheet Suatelier  Kawaii sticker, Cute stickers, Scrapbooking materialPlanner': 1, '1610-Plain 06, 3 sheets Korean Cotton Sticker sheet Suatelier  Kawaii sticker, Cute stickers, Scrapbooking materialPlanner': 1, '1605-Plain 01, 6mm Korean Sticker sheet Suatelier  Kawaii sticker, Cute stickers, Scrapbooking material 3 sheetsPlanner': 1, 'best offer 1 Pen with 5 refills pcs Japan [Muji] MomA 0.38mm/0.5mm Gel INK PEN Black/Blue COLOUR': 1, '1061- daily Korean Travel Sticker sheet Suatelier  Kawaii sticker, Cute stickers, Scrapbooking materialPlanner': 1, '2018 new collection 60 style can choose One of the Limited Japan Kinds Pilot Frixion Stamp SPF-12 erasable scrapbook': 14, 'Zebra Justfit Mojini Line Highlighter - 5 Color Set WKS22-5C': 1, "Let's Color 6 colors fast dry Ink Pads for Fingerprints, Brilliance Drop Ink Pad, Fingerprint Ink Pad, Thumbprint Guest Book": 1, '2019 new collection One of 98-115 the Limited Japan Kinds Pilot Frixion Stamp SPF-12 erasable': 1, '1082 - daily in Tokyo Korean sheet Suatelier  Kawaii sticker, Cute stickers, Scrapbooking materialPlanner': 1, '2018 new collection 72 style can choose One of 61-72 the Limited Japan Kinds Pilot Frixion Stamp SPF-12 erasable scrapbook': 1}

相关问题 更多 >