почему код повторно выводит некторые данные from bs4 import BeautifulSoup import…
- User
почему код повторно выводит некторые данные from bs4 import BeautifulSoup import requests url = f'https://www.poizon.us/collections/sneakers-1?page=20'
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
gf-products > li:nth-child(1) > div > div > div.card__content > div.card__information > h3 > a
links = soup.select('a.full-unstyled-link') for link in links: if link is not None: href = link.get('href') if href is not None: full_link = 'https://www.poizon.us' + href else: print('Ссылка не найдена') continue
response = requests.get(full_link) soup = BeautifulSoup(response.text, 'html.parser') photo_selector = '#Thumbnail-template--16663852253403__main-1' photo_links = soup.select_one(photo_selector).get('srcset').split(', ') photo_link = photo_links[0].split(' ')[0] size_selector = 'div.product-popup-modal__content-info:nth-child(1) > variant-radios:nth-child(1) > fieldset:nth-child(2) > label:nth-child(3) > div:nth-child(1)' price_selector = 'div.product-popup-modal__content-info:nth-child(1) > variant-radios:nth-child(1) > fieldset:nth-child(2) > label:nth-child(3) > div:nth-child(2)' size_element = soup.select_one(size_selector) if size_element is not None: size = size_element.text.strip() else: size = 'Размер не найден' price_element = soup.select_one(price_selector) if price_element is not None: price = price_element.text.strip() else: price = 'Цена не найдена' name_element = soup.select_one('div.product__title > h1:nth-child(1)') if name_element is not None: name = name_element.text.strip() else: name = 'Название не найдено' info_element = soup.select_one('#ProductAccordion-ea1014ee-ae9d-4eee-b23c-d2dfe9ba75b4-template--16663852253403__main') if info_element is not None: info = info_element.text.strip() else: info = 'Информация не найдена' urls = photo_link.replace("//", "https://") url = urls+'111' photo_lin = photo_link.replace('//cdn.shopify.com', 'https://cdn.shopify.com') print(f'Название: {name}\nРазмер: {size}\nИнформация: {info}') print(f"цена: {price} (Цена является ориентировочной, за точной информацией можете обращаться к @egvv6.Обычно цена товара значительно меньше указанной здесь") print(url) - Assistant
Код может повторно выводить некоторые данные из-за того, что BeautifulSoup парсит данные на странице и собирает информацию с элементов, которые соответствуют указанным CSS-селекторам. Если на странице есть повторяющиеся элементы, которые соответствуют этим селекторам, они также будут выбраны.
Также возможно, что один и тот же товар отображается на разных страницах товаров или разделах сайта, и код выбирает их несколько раз. Для того чтобы избежать повторения, следует проверять, был ли товар уже обработан, прежде чем выводить его данные. Например, можно использовать множество (set) для хранения обработанных ссылок и проверять, есть ли ссылка в этом множестве, прежде чем обрабатывать очередной товар:
processed_links = set() for link in links: if link is not None: href = link.get('href') if href is not None: full_link = 'https://www.poizon.us' + href else: print('Ссылка не найдена') continue if full_link in processed_links: continue processed_links.add(full_link) # Здесь обработка товара и вывод информации о немЭтот подход позволит предотвратить повторную обработку и вывод одного и того же товара.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.