Как очистить заголовки гиперссылок с помощью BeautifulSoup? - PullRequest
0 голосов
/ 23 сентября 2019

Итак, веб-сайт, с которого я пытаюсь разобраться: https // viewyourdeal-gabrielsimone.com '

Названия продуктов и цены указаны в каждом разделе div class = "info-wrapper", который я могу извлечьцена без проблем, однако, когда я пытаюсь извлечь название продукта, он не может преобразовать его в текст, как ссылку href.Каждое название продукта находится под классом div под href.Итак, мой вопрос, как мне очистить название продукта?

import json
from bs4 import BeautifulSoup
import requests 
import csv
from datetime import datetime

url = 'https://viewyourdeal-gabrielsimone.com'

gmaInfo=[]
response = requests.get(url, timeout=5)
content = BeautifulSoup(response.content, "html.parser")
for info in content.findAll('div', attrs={"class" : "wrapper ease-animation"}):
    gridObject = {
            "title" : info.find('div', attrs={"class" : "title animation allgrey"}),
            "price" : info.find('span', attrs={"class":"red-price"}).text
            }
    print(gridObject)
    with open('index.csv', 'w') as csv_file:
        writer = csv.writer(csv_file)
        writer.writerow([gridObject])

Ответы [ 2 ]

0 голосов
/ 24 сентября 2019

Я был слишком конкретен с моим классом div, я изменил класс на просто title, и он работал нормально.

0 голосов
/ 24 сентября 2019

С помощью следующего кода немногие элементы возвращаются как None. Просто предоставьте условие If, если элемент существует, получите текст.

from bs4 import BeautifulSoup
import requests
import csv
from datetime import datetime

url = 'https://viewyourdeal-gabrielsimone.com'

gmaInfo=[]
response = requests.get(url, timeout=5)
content = BeautifulSoup(response.content, "html.parser")

for info in content.findAll('div', attrs={"class" : "wrapper ease-animation"}):
   if info.find('div', attrs={"class": "title animation allgrey"}):
     gridObject = {
            "title" : info.find('div', attrs={"class" : "title animation allgrey"}).text.strip(),
            "price" : info.find('span', attrs={"class":"red-price"}).text
            }
     print(gridObject)
     with open('index.csv', 'w') as csv_file:
        writer = csv.writer(csv_file)
        writer.writerow([gridObject])
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...