Как выбрать и получить данные при парсе в Python?
Как сделать запрос, если в одном классе допустим несколько <a href> как выбрать тот который мне нужен? Пытаюсь из <div> класса content_product_catalog_list_item_picture забрать ссылку <a href> на страницу товара, но необходимо выбрать определенную, так как после <div>, <a href> встречается 3 раза
import requests
from bs4 import BeautifulSoup
import csv
HOST = 'https://happywear.ru/'
URL = 'https://happywear.ru/boys/boy-povsednevnaya-odegda/boy-shtani'
HEADERS = {
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',
'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.114 Safari/537.36'
}
def get_html(url, params=''):
r = requests.get(url, headers=HEADERS, params=params)
return r
def get_content(html):
soup = BeautifulSoup(html, 'html.parser')
items = soup.find_all('li', class_='js-catalog-item content_product_catalog_list_item')
cards = []
for item in items:
cards.append(
{
'title': item.find('a', class_='content_product_catalog_list_item_info_introtext').get_text(strip=type),
'title_2': item.find('div', class_='content_product_catalog_list_item_picture').find('a').get_text('href'),
'title_rub': item.find('div', class_='content_product_catalog_list_item_price__block').get_text(strip=type),
'card_img': item.find('div', class_='content_product_catalog_list_item_picture').find('img').get('src')
}
)
return cards
html = get_html(URL)
print(get_content(html.text))
Ответы (2 шт):
Автор решения: Incover
→ Ссылка
Попробуйте по индексу достать из массива который получили. Думаю он всегда будет 1.
Автор решения: Недокодер
→ Ссылка
Ищите по кодовому слову вашу ссылку например:
import re
href = soup.find(href=re.compile("boys")) # Для вашего случая ключевое слово должно бить boys
