Python - очистка веб-страницы для информации, которая появляется только после прокрутки - PullRequest
0 голосов
/ 03 февраля 2019

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

То, что я пытался сделать, это прокрутить до самого концастраницы, так что все аргументы раскрываются (это не занимает много времени, чтобы достичь нижней части страницы), а затем извлекает HTML-код оттуда.

Вот что я сделал.Между прочим, я получил код прокрутки от здесь .

SCROLL_PAUSE_TIME = 0.5

#launch url
url = 'https://en.arguman.org/fallacies'

#create chrome sessioin
driver = webdriver.Chrome()
driver.implicitly_wait(30)
driver.get(url)

#get scroll height
last_height = driver.execute_script("return document.body.scrollHeight")


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

    # Wait to load page
    time.sleep(SCROLL_PAUSE_TIME)

    # Calculate new scroll height and compare with last scroll height
    new_height = driver.execute_script("return document.body.scrollHeight")
    if new_height == last_height:
        break
    last_height = new_height

http = urllib3.PoolManager()
response = http.request('GET', url)
soup = BeautifulSoup(response.data, 'html.parser')

claims_h2 = soup('h2')
claims =[]
for c in claims_h2:
    claims.append(c.get_text())

for c in claims:
    print (c)

Это то, что я получаю, и это все аргументы, которые вы увидите, не прокручивая и добавляя больше на страницу.

Plants should have the right to vote.
Plants should have the right to vote.
Plants should have the right to vote.
Postmortem organ donation should be opt-out
Jimmy Kimmel should not bring up inaction on gun policy (now)
A monarchy is the best form of government
A monarchy is the best form of government
El lenguaje inclusivo es innecesario
Society suffers the most when dealing with people having mental disorders
Illegally downloading copyrighted music and other files is morally wrong.

Если вы посмотрите и прокрутите всю страницу до конца, вы увидите эти аргументы, а также многие другие.

По сути, мой код, похоже, неразбирать обновленный HTML-код.

1 Ответ

0 голосов
/ 03 февраля 2019

Нет смысла открывать сайт с помощью Selenium, выполнять всю прокрутку, а затем повторять запрос с помощью urllib.Два процесса полностью разделены и не связаны между собой.

Вместо этого, когда прокрутка завершена, передайте driver.page_source в BeautifulSoup и извлеките содержимое оттуда:

import time

from bs4 import BeautifulSoup
from selenium import webdriver

driver = webdriver.Chrome()
driver.implicitly_wait(30)

try:
    SCROLL_PAUSE_TIME = 0.5
    driver.get("https://en.arguman.org/fallacies")

    last_height = driver.execute_script("return document.body.scrollHeight")

    while True:
        driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
        time.sleep(SCROLL_PAUSE_TIME)
        new_height = driver.execute_script("return document.body.scrollHeight")
        if new_height == last_height:
            break
        last_height = new_height

    soup = BeautifulSoup(driver.page_source, "html.parser")

    for c in soup("h2"):
        print(c.get_text())

finally:
    driver.quit()

Результат:

Plants should have the right to vote.
Plants should have the right to vote.
Plants should have the right to vote.
Postmortem organ donation should be opt-out
Jimmy Kimmel should not bring up inaction on gun policy (now)
A monarchy is the best form of government
A monarchy is the best form of government
El lenguaje inclusivo es innecesario
Society suffers the most when dealing with people having mental disorders
Illegally downloading copyrighted music and other files is morally wrong.
Semi-colons are pointless in Javascript
You can't measure how good a programming language is.
You can't measure how good a programming language is.
Semi-colons are pointless in Javascript
Semi-colons are pointless in Javascript
Semi-colons are pointless in Javascript
...
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...