Как получить текст тегов привязки, только если он находится внутри абзаца, используя красивый суп? - PullRequest
0 голосов
/ 03 февраля 2020

Я пытаюсь разобрать очищенные данные с красивым супом. Что мне нужно, это получить все видимые данные, которые все данные в статье, и h1. В большинстве случаев данные статьи содержат текст с вложенными в него данными. Что-то вроде "Я" href / good_boy "в моем классе". Теперь я хочу, чтобы этот тег был только в том случае, если он находится внутри абзаца. Ниже приведен мой код.

from selenium import webdriver

    from selenium.webdriver.chrome.options import Options
    import time
    from bs4 import BeautifulSoup
    import json
    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support import expected_conditions as EC
    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.common.exceptions import NoSuchElementException
    from selenium.webdriver.support.ui import Select
    from selenium.webdriver.common.action_chains import ActionChains
    from queue import Queue
    from threading import Thread
    options = Options()
    #data = []
    our_urls = []
    options.add_argument('--ignore-certificate-errors')
    options.add_argument('--incognito')
    #options.add_argument('--headless')
    options.add_argument("--no-sandbox")
    options.add_argument('--disable-dev-shm-usage')


    def foo():
        global our_urls
        with open('input_backup.json') as json_file:
            data = json.load(json_file)
            global our_urls
            our_urls = data['urls']
            return our_urls


    def scraper_worker(q):
     try:
        while not q.empty():
            url = q.get()
            #print(url)
            driver = url[2]
            r = driver.get(url[1])
            last_height = driver.execute_script("return document.body.scrollHeight")

            while True:
                # Scroll down to bottom
                # make_true=False
                driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")

                # Wait to load page
                time.sleep(10)

                # Calculate new scroll height and compare with last scroll height
                new_height = driver.execute_script("return document.body.scrollHeight")
                # soup = BeautifulSoup(driver.page_source, "html.parser")
                # print("inside loop" + driver.current_url + "\n\t" + soup.get_text())
                if new_height == last_height:
                    # If heights are the same it will exit the function
                    break
                last_height = new_height
            driver.execute_script("return document.getElementsByTagName('html')[0].innerHTML")

            soup = BeautifulSoup(driver.page_source, "html.parser")
            whitelist = [
                        'p', 'h1','a'
                     ]

            blackList = [   '[document]',
        'noscript','div',
        'footer',
        'html',
        'meta',
        'head',
        'input',
        'script',]
            text_elements = [t for t in soup.find_all(text=True) if t.parent.name in whitelist]
            print("\n\t" + driver.current_url + "\n\t")
            print(text_elements)
            #page = pyquery(r.text)
            #data = page("#data").text()
            # do something with data
            driver.quit()
            q.task_done()
     except:
         pass

    # Create a queue and fill it
    urls = foo()
    #print(urls)
    mlen = len(urls)
    q = Queue()
    #for x in urls:
      #q.put(x)
    for i in range(len(urls)):
          # need the index and the url in each queue item.
        driver = webdriver.Chrome("./chromedriver", options=options)
        q.put((i, urls[i],driver))
    #map(q.put, urls)

    # Create 5 scraper workers
    for i in range(3):
        t = Thread(target=scraper_worker, args=(q, ))
        t.setDaemon(True)
        t.start()
    #print("waiting for queue to complete", jobs.qsize(), "tasks")
    q.join()

    print("all tasks completed")

Ниже приведен ссылочный URL Пример URL

, а вот вывод

['Mail ',' Новости ',' Финансы ',' Спорт ',' Развлечения ',' Поиск ',' Мобильный телефон ',' Больше ',' Войти ',' response-text: 10 ',' Finance Home ',' / реагирующий текст ',' реактивный текст: 20 ',' списки наблюдения ', / реактивный текст', реактивный текст: 23 ',' мое портфолио ',' / реагирующий текст ',' реактивный текст: 26 ',' Screeners ',' / реагировать-текст ',' реагировать-текст: 29 ',' Премиум ',' / реагировать-текст ',' реагировать-текст: 32 ',' Рынки ',' / реагировать-текст ' , 'Reaction-Text: 35', 'Индустрии', '/ Reaction-Text', 'реагировать-текст: 38', 'Личные финансы', '/ реагировать-текст', 'реагировать-текст: 41', 'Видео ',' / реагировать-текст ',' реагировать-текст: 44 ',' Новости ',' / реагировать-текст ',' реагировать-текст: 47 ',' Технология ',' / реагировать-текст ',' S & P 500 ',' Dow 30 ',' Nasdaq ',' Russell 2000 ',' Crude Oil ',' Tethers Unlimited говорят, что 'Terminator Tape' ускоряет спуск спутника по назначению ',' GeekWire ',' Bothell, Wa sh на основе ',' Tethers Unlimi Тед, - говорит «Терминаторная лента», - экспериментальная система на основе привязи, предназначенная для перетаскивания спутников с орбиты, работает так, как она должна. Ракета SpaceX Falcon Heavy, - говорится в пресс-релизе, - сотрудничает с космическими системами Millennium, TriSept и Rocket Lab в ходе испытательной миссии, известной как DragRacer, - сказал Хойт Space News, - робот обслуживания LEO Knight, - Tethers Unlimited объединяет усилия с TriSept для тестирования системы уменьшения количества орбитального мусора »,« Tethers Unlimited работает над технологиями для «робота обслуживания спутников LEO Knight», «Tethers Unlimited говорит, что двусторонняя радиосвязь для малых спутников прошла первый орбитальный тест», Tethers Unlimited поднимает на меня занавес * Сетевая система sh для малых спутников ',' Kolte Patil - Ivy Nia ',' Ad ',' Maruti Suzuki ',' Ad ',' Fateheducation ',' Ad ',' hear.com ',' Ad '] все задачи выполнены.

Так может кто-нибудь, пожалуйста, помогите мне, как получить только текст статьи wi Заголовок и абзац между ними. Я не получаю желаемый результат, как

Bothell, Wa sh. На основе Tethers Unlimited говорит «Terminator Tape», экспериментальная система на основе привязи, предназначенная для перетаскивания спутников с орбиты, работает так, как она должен.

The notebook-sized Terminator Tape system has been placed on several nanosatellites for testing — including Georgia Tech’s Prox-1 satellite, which was sent into orbit last June on a SpaceX Falcon Heavy rocket. Last September, the system’s 230-foot-long tether was strung out to add to the slight atmospheric drag experienced in low Earth orbit. “We can see from observations by the U.S. Space Surveillance Network that the satellite immediately began deorbiting over 24 times faster,” Tethers Unlimited CEO Rob Hoyt said in a news release.
That’s a good thing: Terminator Tape is meant to address the need to move retired satellites more quickly out of orbit, rather than having them add to the growing space-junk problem. “Instead of remaining in orbit for hundreds or thousands of years, the Prox-1 satellite will fall out of orbit and burn up in the upper atmosphere in under 10 years. … This successful test proves that this lightweight and low-cost technology is an effective means for satellite programs to meet orbital debris mitigation requirements,” Hoyt said.
Tethers Unlimited is currently collaborating with Millennium Space Systems, TriSept and Rocket Lab on a test mission known as DragRacer, due for launch this year. The mission will compare the deorbit rates for two identical satellites, one with Terminator Tape and one without, to characterize the system’s performance more precisely. Hoyt told Space News that in the years ahead, the system could be attached to defunct satellites in orbit using Tethers Unlimited’s planned LEO Knight servicing robot.
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...