Python 抓取使用AJAX Post填充数据的网站

Python 抓取使用AJAX Post填充数据的网站,python,html,ajax,web-scraping,beautifulsoup,Python,Html,Ajax,Web Scraping,Beautifulsoup,我想知道是否有可能使用beautifulsoup删除一个基于ajax调用加载表的网站 下面是我用来访问包含该表的div的python代码 table=bs.find(lambda标记:tag.name=='div'和tag.has_key('id')和tag['id']=='id+name”) 当执行该命令时,我得到一个空div java脚本/ajax函数如下所示 function getTable(){ $.ajax({ type: "POST", ur

我想知道是否有可能使用
beautifulsoup
删除一个基于ajax调用加载表的网站

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

table=bs.find(lambda标记:tag.name=='div'和tag.has_key('id')和tag['id']=='id+name”)

当执行该命令时,我得到一个空div

java脚本/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);
        }
    });
函数getTable(){
$.ajax({
类型:“POST”,
url:“”,
contentType:“应用程序/json;字符集=utf-8”,
数据类型:“json”,
成功:功能(msg){
$('#table+id').html(msg.d);
}
});

我想我会变得空白,因为它试图在处理页面之前刮表。这是可以在beautiful soup中处理的东西吗?

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

基本上,您有两种选择:

  • 使用一个利用真实浏览器的工具,比如。这样你就可以让浏览器为你完成加载页面和执行javascript的所有工作。你可以使用它来访问元素
  • 使用或发出
    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'])
    
    印刷品:

    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中尝试了它,当我使用完整的url(站点+处理文件)时,它也以无JSON对象的形式返回我得到了200的回报,我假设这意味着它在那里,但不会返回任何东西*更新-发现我得到了200,因为他们有一个404页面设置redirect@Alex好的,你能提供一个链接,这样我可以重现这个问题吗?
    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 
    ...