Перемещение по HTML веб-сайта с использованием красивого супа на python - PullRequest
0 голосов
/ 05 августа 2020

Я пытаюсь перейти по ссылке href внутри вложенного class на веб-сайте. У меня возникли проблемы с выбором определенных c продуктов href.

Это мой код:

r = requests.get('https://kith.com/collections/mens-footwear-sneakers')
Page = bs4.BeautifulSoup(r.text, "lxml")
soup = BeautifulSoup(r.content,'html.parser')
tester = soup.find(class_='collection_products').find(class_='collection-product').find_all('product-card__information')
print(tester)

Однако я продолжаю получать эту ошибку при запуске моего кода:

tester = soup.find(class_='collection_products').find(class_='collection-pr
oduct').find_all('product-card__information')
AttributeError: 'NoneType' object has no attribute 'find'

Как найти href внутри html, вложенного в несколько классов? Здесь изображение html на сайте.

1 Ответ

0 голосов
/ 05 августа 2020

Используйте селектор CSS, чтобы выбрать class.

Этот скрипт найдет все ссылки в классе product-card__information

import requests
from bs4 import BeautifulSoup

BASE = 'https://kith.com/collections/mens-footwear-sneakers'

r = requests.get('https://kith.com/collections/mens-footwear-sneakers')
soup = BeautifulSoup(r.content, 'html.parser')

# Select the class using a CSS Selector
for i in soup.select('.product-card__information'):
    # find the href under the anchor `a` tag
    print(BASE + i.a['href'])

Выходы

https://kith.com/collections/mens-footwear-sneakers/products/nkcw7297-100
https://kith.com/collections/mens-footwear-sneakers/products/nkcz0614-700
https://kith.com/collections/mens-footwear-sneakers/products/nkcu9180-101
https://kith.com/collections/mens-footwear-sneakers/products/pu37488101
https://kith.com/collections/mens-footwear-sneakers/products/pu37487501
https://kith.com/collections/mens-footwear-sneakers/products/pu37487401
https://kith.com/collections/mens-footwear-sneakers/products/pu37487201
... and on
...