【问题标题】:Parsing data scraped from Javascript rendered webpage with python使用 python 解析从 Javascript 呈现的网页中抓取的数据
【发布时间】:2021-08-10 04:42:03
【问题描述】:

我正在尝试使用 .find 关闭一个汤变量,但是当我转到网页并尝试找到正确的类时,它没有返回。

from bs4 import *
import time
import pandas as pd
import pickle
import html5lib
from requests_html import HTMLSession

s = HTMLSession()
url = "https://cryptoli.st/lists/fixed-supply"


def get_data(url):
    r = s.get(url)
    global soup
    soup = BeautifulSoup(r.text, 'html.parser')
    return soup

def get_next_page(soup):
    page = soup.find('div', {'class': 'dataTables_paginate paging_simple_numbers'})
    return page
    
get_data(url)
print(get_next_page(soup))

“page”变量返回“None”,即使我从网站元素检查器中提取了它。我怀疑这与网站是用 javascript 呈现但无法弄清楚原因有关。如果我拿走 {'class' : ''datatables_paginate paging_simple_numbers'} 并尝试找到 'div' 然后它会工作并返回第一个 div 标签,所以我不知道还能做什么。

【问题讨论】:

  • 现代页面可能使用 JavaScript 添加元素,而 BS 无法运行 JavaScript。您可能需要selenium 来控制可以运行 JavaScript 的真实网络浏览器。您可以在浏览器中关闭 JavaScript 并重新加载页面以查看页面是否使用 JavaScript。
  • 此页面可能包含 HTML 中的所有数据,但在 <script> 中为 cl.coinmainlist.dataraw = [ ...],但他们需要一些工具将其转换为有用的东西 - 这可能是问题所在。

标签: python web-scraping


【解决方案1】:

所以你想抓取动态页面内容,你可以用selenium webdriver的美汤。此答案基于此处的解释 https://www.geeksforgeeks.org/scrape-content-from-dynamic-websites/

from selenium import webdriver
from selenium.webdriver.common.keys import Keys

url = "https://cryptoli.st/lists/fixed-supply"
  
driver = webdriver.Chrome('./chromedriver') 
driver.get(url) 
  
# this is just to ensure that the page is loaded
time.sleep(5) 
  
html = driver.page_source
  
# this renders the JS code and stores all
# of the information in static HTML code.
  
# Now, we could simply apply bs4 to html variable
soup = BeautifulSoup(html, "html.parser")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-01-12
    • 1970-01-01
    • 2019-06-13
    • 2019-04-05
    • 1970-01-01
    • 2013-10-12
    • 2019-06-15
    • 2021-02-28
    相关资源
    最近更新 更多