Как использовать BeautifulSoup для чистки - PullRequest
0 голосов
/ 21 ноября 2018

Целью скрипта является посещение веб-сайта, который затем генерирует список ссылок для всех продуктов, использующих селен, через get_attribute.

Используя запросы, я посещаю каждую из этих вновь созданных ссылок, чтобы посетить каждый продукт.Затем я пытаюсь очистить хранилище BeautifulSoup с различными характеристическими переменными.

Моя проблема в том, что я считаю, что некоторые из продуктов, которые я пытаюсь очистить, не имеют категории, которую я пытаюсь очистить, однако, я полагаю, что большинство из них имеют.Есть ли способ вернуть что-то вроде «N / A» для продуктов, которые не имеют сохраненной характеристики, которую я очищаю?

Вот мой код:

import time
import csv
from selenium import webdriver
import selenium.webdriver.chrome.service as service
import requests
from bs4 import BeautifulSoup

all_product = []

url = "https://www.vatainc.com/infusion.html?limit=all"
service = service.Service('/Users/Jonathan/Downloads/chromedriver.exe')
service.start()
capabilities = {'chrome.binary': '/Google/Chrome/Application/chrome.exe'}
driver = webdriver.Remote(service.service_url, capabilities)
driver.get(url)
time.sleep(2)
links = [x.get_attribute('href') for x in driver.find_elements_by_xpath("//*[contains(@class, 'product-name')]/a")]

for link in links:
    html = requests.get(link).text
    soup = BeautifulSoup(html, "html.parser")
    products = soup.findAll("html")

    for product in products:
        name = product.find("div", {"class": "product-name"}).text.strip('\n\r\t": ')
        manufacturing_SKU = product.find("span", {"class": "i-sku"}).text.strip('\n\r\t": ')
        manufacturer = product.find("p", {"class": "manufacturer"}).text.strip('\n\r\t": ')
        description = product.find("div", {"class": "std description"}).text.strip('\n\r\t": ')
        included_products = product.find("div", {"class": "included_parts"}).text.strip('\n\r\t": ')
        price = product.find("span", {"class": "price"}).text.strip('\n\r\t": ')
        all_product.append([name, manufacturing_SKU, manufacturer, description, included_products, price])
print(all_product)

Вот мойкод ошибки:

 AttributeError                            Traceback (most recent call last)
<ipython-input-25-36feec64789d> in <module>()
     34         manufacturer = product.find("p", {"class": "manufacturer"}).text.strip('\n\r\t": ')
     35         description = product.find("div", {"class": "std description"}).text.strip('\n\r\t": ')
---> 36         included_products = product.find("div", {"class": "included_parts"}).text.strip('\n\r\t": ')
     37         price = product.find("span", {"class": "price"}).text.strip('\n\r\t": ')
     38         all_product.append([name, manufacturing_SKU, manufacturer, description, included_products, label, price])

AttributeError: 'NoneType' object has no attribute 'text'

1 Ответ

0 голосов
/ 21 ноября 2018

Метод find() для вашего BeautifulSoup объекта возвращает None, когда он не может найти элемент DOM, соответствующий вашему запросу.В частности, в этой строке included_products он не может найти div с классом included_parts.

. Вы можете сделать что-то подобное, чтобы получить included_products значение None в этом случае.:

def find_with_class(soup, tag_type, class_name):
    elements = soup.find(tag_type, {'class': class_name})
    if elements:
        return elements.text.strip('\n\r\t": ')
    else:
        return None

included_products = find_with_class(product, 'div', 'included_parts')
...