Динамическая обработка страниц c HTML структура страницы - PullRequest
0 голосов
/ 17 апреля 2020

Я работаю над масштабным веб-проектом, в котором структура HTML каждой веб-страницы отличается друг от друга. Я хотел соскрести описание продукта с веб-страниц и использую пакет BeautifulSoup.

Например, описание продукта, которое я пытаюсь очистить, хранится в HTML структурах:

<div class="product-description">
  <p> "Title" </p>
  <p> "Some content" </p>
  <p> "Product description" </p>
</div>


<div class="product-description">
  <p> "Title" </p>
  <p> "Product description" </p>
</div>

<div class="product-description">
  <p> "Title" </p>
  <p> "Some content" </p>
  <p> "Some content" </p>
  <p> "Product description" </p>
</div>


<div class="product-description">
  <p> "Title" </p>
  <p> "Some-content" </p>
  <p> "Some-content" </p>
  <p> "Some-content" </p>
  <p> "Product description" </p>
</div>

Я написал для l oop, который получает данные из класса div "product-description" в зависимости от структуры страницы. Мой пример кода:

requests = (grequests.get(url) for url in urls)
responses = grequests.imap(requests, grequests.Pool(1000))

for response in responses:

        html_soup = BeautifulSoup(response.text, 'html.parser')

        if html_soup.find('div',class_='product_description').next_element.next_sibling.next_sibling.next_sibling.next_sibling:
                product_description = html_soup.find('div',class_='product_description').next_element.next_sibling.next_sibling.next_sibling.next_sibling.text

        elif html_soup.find('div', class_='product-description').next_element.next_sibling.next_sibling.next_sibling:
                product_description = html_soup.find(
                  'div', class_='product_description').next_element.next_sibling.next_sibling.next_sibling.text

        elif html_soup.find('div', class_='product-description').next_element.next_sibling.next_sibling:
                product_description = html_soup.find(
                  'div', class_='product_description').next_element.next_sibling.next_sibling.text

        else:
                product_description = html_soup.find(
                  'div', class_='product_description').next_element.next_sibling.text

Я ожидал, что условия if будут проверять, есть ли братья и сестры на текущем уровне HTML, а если нет, проверять последующие условия. Однако после 3000 итераций я получаю Attribute error, говорящий Nonetype object has no attribute next_sibling. Снимок экрана, прикрепленный ниже:

Attribute error

Я знаю, что должен быть какой-то другой более простой способ обработки этой динамической c структуры страницы. Любая помощь приветствуется. Заранее спасибо!

1 Ответ

1 голос
/ 17 апреля 2020

Попробуйте:

for i in soup.find_all('div',class_="product-description"):
    try:
        print(i.find_all('p')[-1].text)
    except:
        pass

Вот суп:

<div class="product-description">
  <p> "Title" </p>
  <p> "Some content" </p>
  <p> "Product description" </p>
</div>


<div class="product-description">
  <p> "Title" </p>
  <p> "Product description" </p>
</div>

<div class="product-description">
  <p> "Title" </p>
  <p> "Some content" </p>
  <p> "Some content" </p>
  <p> "Product description" </p>
</div>


<div class="product-description">
  <p> "Title" </p>
  <p> "Some-content" </p>
  <p> "Some-content" </p>
  <p> "Some-content" </p>
  <p> "Product description" </p>
</div>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...