【问题标题】:Trouble parsing deeply-nested HTML with BeautifulSoup使用 BeautifulSoup 解析深度嵌套的 HTML 时遇到问题
【发布时间】:2021-05-27 11:39:15
【问题描述】:

对于上下文,我对 Python 还是很陌生。我正在尝试使用 bs4 从https://bigfuture.collegeboard.org/college-university-search/university-of-california-los-angeles 中解析一些数据

确切地说,我想在网页的“支付”部分获取 57% 的数字。 我的问题是bs4只会返回HTML的第一层,而我想要的数据是深深嵌套在代码中的。我认为它低于 17 个 div。

这是我的python代码:

import requests
import bs4

url = 'https://bigfuture.collegeboard.org/college-university-search/university-of-california-los-angeles'

res = requests.get(url)
soup = bs4.BeautifulSoup(res.text, "html.parser")
print(soup.find_all("div", {"id": "gwtDiv"}))

(这会返回[<div class="clearfix margin60 marginBottomOnly" id="gwtDiv" style="min-height: 300px;height: 300px;height: auto;"></div>] 里面的元素都不显示。)

【问题讨论】:

    标签: python html web-scraping beautifulsoup


    【解决方案1】:

    如果页面使用 js 在元素内呈现内容,则请求将无法获取该内容,因为该内容是在浏览器的客户端呈现的。我建议将 ChromeDriver 和 Selenium 与 BeautifulSoup 一起使用。

    您可以从这里下载 chrome 驱动程序:https://chromedriver.chromium.org/ 将其放在运行程序的同一文件夹中。

    试试这样的

    from selenium import webdriver
    from bs4 import BeautifulSoup
    
    url = 'https://bigfuture.collegeboard.org/college-university-search/university-of-california-los-angeles'
    
    driver = webdriver.Chrome()
    driver.get(url)
    
    html = driver.execute_script("return document.documentElement.outerHTML")
    sel_soup = BeautifulSoup(html, 'html.parser')
    print(soup.find_all("div", {"id": "gwtDiv"}))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-07-16
      • 2023-03-27
      • 2013-07-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-08
      • 1970-01-01
      相关资源
      最近更新 更多