【问题标题】:Python Selenium: How to get updated HTML DOM after scrolling down?Python Selenium:向下滚动后如何获取更新的 HTML DOM?
【发布时间】:2016-12-06 02:00:20
【问题描述】:

我正在访问一个实现视差滚动的page。我正在使用代码滚动底部,但 BeautifulSoup 它没有获取更新的 DOM。代码如下:

import requests
from bs4 import BeautifulSoup
from gensim.summarization import summarize

from selenium import webdriver
from datetime import datetime
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.keys import Keys
from time import sleep
import sys
import os
import xmltodict
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
import traceback
import random

driver = None
driver = webdriver.Firefox()
driver.maximize_window()
def fetch_links(tag):
    links = []
    url = 'https://steemit.com/trending/'+tag
    driver.get(url)
    html = driver.page_source
    sleep(4)

    soup = BeautifulSoup(html,'lxml')
    entries = soup.select('.entry-title > a')
    driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
    driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
    sleep(5)
    entries = soup.select('.entry-title > a')
    for e in entries:
        if e['href'].strip() not in entries:
            links.append(e['href'])
    return links

【问题讨论】:

    标签: python selenium


    【解决方案1】:

    您可能需要在窗口滚动后解析页面:

    driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
    driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
    
    sleep(5)
    
    soup = BeautifulSoup(driver.page_source, 'lxml')
    entries = soup.select('.entry-title > a')
    

    【讨论】:

    • 看来问题出在BeautifulSoup。所有标题都存在于driver.page_source返回的html中。
    • 默认每页选择 20 条记录,滚动时应该选择下一个 20
    • 作为替代方案,您可以通过一个 JavaScript 调用直接提取所有链接:links = driver.execute_script("return [].map.call(document.querySelectorAll(".entry-title > a"), e => e.href)")
    • 它如何选择尚未成为 DOM 一部分的链接?
    • 从我执行的测试来看,新链接存在于 DOM 中。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-19
    • 1970-01-01
    • 2018-06-08
    • 2020-08-31
    • 2019-03-29
    • 1970-01-01
    相关资源
    最近更新 更多