【问题标题】:scraping greatschools.org using BeautifulSoup returns empty list使用 BeautifulSoup 抓取 greatschools.org 会返回空列表
【发布时间】:2019-01-03 13:50:07
【问题描述】:

我一直在学习如何使用 BeautifulSoup 抓取 greatschools.org 网站。尽管在这里和其他地方查找了不同的解决方案,但我已经陷入了死胡同。 通过使用 chrome 上的“检查”功能,我可以看到该网站有表格标签,但 find_all('tr') 或 find_all('table') 或 find_all('tbody') 返回一个空列表。我错过了什么?

这是我正在使用的代码块:

import requests
from bs4 import BeautifulSoup

url = "https://www.greatschools.org/pennsylvania/bethlehem/schools/? 
tableView=Overview&view=table"
page_response = requests.get(url)
content = BeautifulSoup(page_response.text,"html.parser")

table=content.find_all('table')
table

输出为:[]

提前感谢您的帮助。

【问题讨论】:

    标签: python beautifulsoup


    【解决方案1】:

    您可以使用Selenium,因为它看起来像页面是动态的。如果您愿意,您仍然可以使用 beautifulsoup 进行解析。当涉及到标签作为表格时,我选择使用 pandas 来读取 html。您必须做一些工作来拆分文本/列,以及第一列中不应该做的事情。)

    让我知道这是否适合你。

    import pandas as pd
    from selenium import webdriver
    
    url = "https://www.greatschools.org/pennsylvania/bethlehem/schools/?tableView=Overview&view=table"
    
    driver = webdriver.Chrome('C:\chromedriver_win32\chromedriver.exe')
    driver.get(url)
    
    html = driver.page_source
    
    table = pd.read_html(html)
    df = table[0]
    
    driver.close()
    

    输出

    print (table[0])
                                                   School                       ...                                                              District
    0   9/10Above averageSouthern Lehigh Intermediate ...                       ...                                       Southern Lehigh School District
    1   8/10Above averageHanover El School3890 Jackson...                       ...                                        Bethlehem Area School District
    2   8/10Above averageLehigh Valley Charter High Sc...                       ...                        Lehigh Valley Charter High School For The Arts
    3   6/10AverageCalypso El School1021 Calypso Ave, ...                       ...                                        Bethlehem Area School District
    4   6/10AverageMiller Heights El School3605 Allen ...                       ...                                        Bethlehem Area School District
    5   6/10AverageAsa Packer El School1650 Kenwood Dr...                       ...                                        Bethlehem Area School District
    6   6/10AverageLehigh Valley Academy Regional Cs15...                       ...                                     Lehigh Valley Academy Regional Cs
    7   5/10AverageNortheast Middle School1170 Fernwoo...                       ...                                        Bethlehem Area School District
    8   5/10AverageNitschmann Middle School1002 West U...                       ...                                        Bethlehem Area School District
    9   5/10AverageThomas Jefferson El School404 East ...                       ...                                        Bethlehem Area School District
    10  4/10Below averageJames Buchanan El School1621 ...                       ...                                        Bethlehem Area School District
    11  4/10Below averageLincoln El School1260 Gresham...                       ...                                        Bethlehem Area School District
    12  4/10Below averageGovernor Wolf El School1920 B...                       ...                                        Bethlehem Area School District
    13  4/10Below averageSpring Garden El School901 No...                       ...                                        Bethlehem Area School District
    14  4/10Below averageClearview El School2121 Abing...                       ...                                        Bethlehem Area School District
    15  4/10Below averageLiberty High School1115 Linde...                       ...                                        Bethlehem Area School District
    16  4/10Below averageEast Hills Middle School2005 ...                       ...                                        Bethlehem Area School District
    17  4/10Below averageFreedom High School3149 Chest...                       ...                                        Bethlehem Area School District
    18  3/10Below averageMarvine El School1425 Livings...                       ...                                        Bethlehem Area School District
    19  3/10Below averageWilliam Penn El School1002 Ma...                       ...                                        Bethlehem Area School District
    20  3/10Below averageLehigh Valley Dual Language C...                       ...                            Lehigh Valley Dual Language Charter School
    21  2/10Below averageBroughal Middle School114 Wes...                       ...                                        Bethlehem Area School District
    22  2/10Below averageDonegan El School1210 East 4t...                       ...                                        Bethlehem Area School District
    23  2/10Below averageFountain Hill El School1330 C...                       ...                                        Bethlehem Area School District
    24  Currently unratedSt. Anne School375 Hickory St...                       ...                                                                   NaN
    
    [25 rows x 7 columns]
    

    现在,如果您仍想使用 BeautifulSoup,因为您可能还尝试提取其中一些链接或表格中的其他标签(也许仅获取表格不足以满足您的需求? ),一旦获得page_response,您就可以像往常一样继续使用 bs4。

    from bs4 import BeautifulSoup
    from selenium import webdriver
    
    url = "https://www.greatschools.org/pennsylvania/bethlehem/schools/?tableView=Overview&view=table"
    
    driver = webdriver.Chrome('C:\chromedriver_win32\chromedriver.exe')
    driver.get(url)
    
    page_response = driver.page_source
    
    content = BeautifulSoup(page_response,'html.parser')  
    table=content.find_all('table')
    table
    
    driver.close()
    

    【讨论】:

    • 感谢您的回复。我可以理解网站的动态性质是问题所在。看来我无法在笔记本电脑上运行 chromedriver.exe。这是我得到的错误:“WebDriverException:消息:'chromedriver.exe' 可执行文件需要在 PATH 中。请参阅sites.google.com/a/chromium.org/chromedriver/home”可能是我的工作笔记本电脑及其 IT 安全策略的问题?
    • 确保路径正确。对我来说,它是'C:\chromedriver_win32\chromedriver.exe',对你来说可能会有所不同。只是保存在哪里。我在工作笔记本电脑上遇到了同样的问题,现在它可以正常工作了,所以driver = webdriver.Chrome('/path/to/chromedriver.exe')
    • 这样做但发现“管理员已禁用加载解压扩展”。期待谷歌,看看我是否可以绕过这个。
    • 啊。那么你可能需要管理员访问权限。其他选项是requests-HTML 包。有一个选项可以让页面在拉取 html 之前呈现。我没有使用它,因为我喜欢使用 Spyder 并且有一个错误不允许它通过该 IPython 控制台正常工作,所以我从未使用过文档中描述的r.html.render()。我也不确定您是否可以使用 BeautifulSoup 进行解析,或者完全使用该包是否简单。但你也可以调查一下
    • 实际上@ph03nix,ewwink 刚刚在上面发布了一个解决方案。他非常擅长处理包含 JSON 数据的动态页面,因为他通常会以更好的方式跟进我对 Selenium 的回答。我仍在学习这一点,所以总是很高兴看到他不使用 Selenium 的替代解决方案。
    【解决方案2】:

    该表是由 Javascript 生成的,但在页面源中有该表的 JSON 数据。

    要获取数据,您可以使用BeautifulSoupjson

    page_response = requests.get(url)
    content = BeautifulSoup(page_response.text, "html.parser")
    scripts = content.find_all('script')
    jsonObj = None
    for script in scripts:
        if 'gon.search' in script.text:
            jsonStr = script.text.split('gon.search=')[1].split(';')
            jsonObj = json.loads(jsonStr[0])
    
    for school in jsonObj['schools']:
        print(school['name'])
    

    或使用rejson

    page_response = requests.get(url)
    jsonStr = re.search(r'gon.search=(.*?);', page_response.text).group(1)
    jsonObj = json.loads(jsonStr)
    for school in jsonObj['schools']:
        print(school['name'])
    

    【讨论】:

      猜你喜欢
      • 2021-11-15
      • 2021-10-27
      • 2018-06-26
      • 1970-01-01
      • 2021-10-04
      • 2017-10-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多