Проблема с веб-очисткой при использовании BeautifulSoup - PullRequest
0 голосов
/ 04 марта 2019

Проблема очистки веб-страниц (снимок экрана прилагается)

def get_text(value):
tdlist = []
for i in soup.findAll(value): # Reduce data to those with html tag 
    if i.text != "":
        text = i.text
        text = text.strip()
        if '\n' not in text: # Remove unnecessary data
            tdlist.append(text)
return tdlist

Master_df = pd.DataFrame()
logs = []

hh = 0
for tag in df_F['Value']:  

    print(hh)
    hh =  hh + 1

    try:
        url = 'https://www.ayurveda.com' + tag

        #weblink to scrape
        html = urlopen(url)
        y = html.read()

        # Page title is:  Scraping 
        soup = BeautifulSoup(y, 'html.parser') # Parse resulting source

        c_list = []
        Title = []


        for value in ['p']:
            c_list = get_text(value)

        for tes in soup.findAll('h1'):
            Title = tes.text

        com_list = c_list
        com_list = '. '.join(com_list)
        com_list = com_list.replace('..',". ")

        com_list1 = Title

        df_each = pd.DataFrame(columns = ["URL","Title","Content","Category","Website"],index = range(0,1))

       df_each["URL"] = url
       df_each["Content"] = com_list
       df_each["Title"] = com_list1
       df_each["Category"] = 'Ayurveda'
       df_each["Website"] = 'Ayurveda'

       Master_df = Master_df.append(df_each)
   except Exception as e:
       print("Hey!, check this :",str(e))
       logs.append(str(e))
#

[Попытка загрузки содержимого на веб-сайте.Это 2 важные сведения, загружаемые с веб-сайта.

1) Заголовок в столбце (помечен в «заголовке») - это понятно.Я получаю правильную информацию. 2) Содержимое в другой колонке (помечено буквой «p»). У меня проблема с получением этой информации.

Ниже приведена информация с веб-сайта:

Ниже строки, которую я мог бы почистить(выделено жирным шрифтом и курсивом)

"от Vasant Lad, BAM & S, MASc"

Ниже линии я не смог поцарапать (отмечено наи курсивом)

Многие ученые считают аюрведу древнейшей целительской наукой.На санскрите Аюрведа означает «Наука Жизни». Аюрведические знания зародились в Индии более 5000 лет назад и часто называются «Матерью Всех Исцелений». Они происходят из древней ведической культуры и преподавались в течение многих тысяч лет.устная традиция от опытных мастеров до своих учеников.Некоторые из этих знаний были напечатаны несколько тысяч лет назад, но большая их часть недоступна.Принципы многих естественных систем исцеления, которые сейчас известны на Западе, берут свое начало в аюрведе, включая гомеопатию и полярную терапию.

.] 2

1 Ответ

0 голосов
/ 05 марта 2019

Причина, по которой вы не получаете абзац, заключается в следующем:

if '\n' not in text:

Требуемый абзац:

'Ayurveda is considered by many scholars to be the oldest healing science. In Sanskrit, Ayurveda means “The Science of Life.” Ayurvedic knowledge originated\n    in India more than 5,000 years ago and is often called the “Mother of All Healing.” It stems from the ancient Vedic culture and was taught for many\n    thousands of years in an oral tradition from accomplished masters to their disciples. Some of this knowledge was set to print a few thousand years\n    ago, but much of it is inaccessible. The principles of many of the natural healing systems now familiar in the West have their roots in Ayurveda, including\n    Homeopathy and Polarity Therapy.'

HAS \n, поэтому он не добавляетсяэтот текст к вашему tdlist.Когда вы используете .strip(), он удалит только эти новые строки и пробелы в начале и конце строки.Поэтому вам нужно найти другое условие.

Таким образом, вы можете просто добавить дополнительное условие, которое захватывает тот конкретный контент, который следует за тегом <p class="bitter">

Я предполагаю, что все ссылкиследуя этому формату.

Измените свою функцию:

def get_text(value):
    tdlist = []
    for i in soup.findAll(value): # Reduce data to those with html tag 
        if i.text != "":
            text = i.text
            text = text.strip()
            if '\n' not in text or i.find_previous(value).attrs == {'class': ['bitter']}: # Remove unnecessary data
                tdlist.append(text)
    return tdlist 

Вывод:

print (c_list)
['by Vasant Lad, BAM&S, MASc', 'Ayurveda is considered by many scholars to be the oldest healing science. In Sanskrit, Ayurveda means “The Science of Life.” Ayurvedic knowledge originated\n    in India more than 5,000 years ago and is often called the “Mother of All Healing.” It stems from the ancient Vedic culture and was taught for many\n    thousands of years in an oral tradition from accomplished masters to their disciples. Some of this knowledge was set to print a few thousand years\n    ago, but much of it is inaccessible. The principles of many of the natural healing systems now familiar in the West have their roots in Ayurveda, including\n    Homeopathy and Polarity Therapy.', 'Copyright © 2006, Vasant Lad, MASc, and The Ayurvedic Institute. All Rights Reserved.', 'Copyright © 2006, Vasant Lad, MASc, and The Ayurvedic Institute. All Rights Reserved.']
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...