【问题标题】:Scraping a website that uses AJAX Post to populate the data抓取使用 AJAX Post 填充数据的网站
【发布时间】:2014-07-11 21:41:17
【问题描述】:

我想知道是否有可能使用beautifulsoup 来抓取一个基于 ajax 调用加载表格的网站。

下面是我用来访问包含表格的 div 的 python 代码

table = bs.find(lambda tag: tag.name=='div' and tag.has_key('id') and tag['id']=="id+name")

执行该操作时,我得到一个空 div <div id="id+name"></div>

java script/ajax 函数长这样

function getTable(){
    $.ajax({
        type: "POST",
        url: "<some processing file .asmx>",
        contentType: "application/json; charset=utf-8",
        dataType:"json",
        success: function(msg){
            $('#table+id').html(msg.d);
        }
    });

我想我会变得空白,因为它试图在处理页面之前抓取表格。这是美汤能搞定的东西吗?

【问题讨论】:

    标签: python html ajax web-scraping beautifulsoup


    【解决方案1】:

    BeautifulSoup 只是一个 HTML 解析器。您需要一些东西来执行该 javascript 调用和/或发出 POST 请求。

    基本上,您有两种选择:

    • 使用使用真实浏览器的工具,例如selenium。这样,您就可以让浏览器为您完成加载页面和执行 javascript 的所有工作。您可以使用find_element_by_id() 来访问元素。
    • 使用urllib2requests 发出POST 请求并解析结果。根据您提供的 javascript 代码 - 响应采用 JSON 格式,其中包含内部表格的 HTML 代码:

      import json
      
      from bs4 import BeautifulSoup
      import requests
      
      URL = "<some processing file .asmx>"
      response = requests.post(URL)
      data = json.loads(response.content)
      
      div = BeautifulSoup(data['d'])
      

    UPD(获取表格的实际工作代码):

    import json
    from bs4 import BeautifulSoup
    
    import requests
    
    
    URL = 'http://www.ise.com/MarketDataService.asmx/ISE_Get_IntraDay_Summary'
    response = requests.post(URL, headers={'Content-Type': 'application/json; charset=utf-8'})
    data = json.loads(response.content)
    
    soup = BeautifulSoup(data['d'])
    for row in soup('tr'):
        print " | ".join(cell.text for cell in row('td'))
    

    打印:

    All Securities  | All Equities Only | All Indices & ETF Only
    16:15 | 244,754 | 258,519 | 503,273 | 95 | 192,025 | 85,778 | 277,803 | 224 | 52,726 | 172,741 | 225,467 | 31
    16:10 | 244,473 | 260,881 | 505,354 | 94 | 192,025 | 85,778 | 277,803 | 224 | 52,445 | 175,103 | 227,548 | 30
    15:50 | 232,697 | 227,149 | 459,846 | 102 | 182,351 | 81,672 | 264,023 | 223 | 50,343 | 145,477 | 195,820 | 35 
    ...
    

    【讨论】:

    • 您有什么建议吗?
    • @Alex 当然,给我一秒钟,说明了这一点,但我正在改进答案。谢谢。
    • 感谢您的建议。我想我会选择选项 2,但是处理文件是相对路径。当我将该相对路径与浏览器中的路径相结合时(没有向上移动),我得到一个不存在的页面。也在 python 中尝试过,结果没有 JSON 对象返回
    • 另外,当我使用完整的 url(站点 + 处理文件)时,我得到 200 的回报,我假设这意味着它在那里,但不会返回任何东西 *更新 - 发现我得到了 200因为他们将页面设置为 404 重定向
    • @Alex 好的,你能提供一个链接,以便我重现问题吗?
    猜你喜欢
    • 1970-01-01
    • 2016-04-18
    • 2011-06-01
    • 2019-11-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多