【问题标题】:Scrape table within a webpage?在网页中抓取表格?
【发布时间】:2014-04-03 16:26:06
【问题描述】:

我目前正在尝试从网页中的表格中抓取所有结果。目前我正在尝试使用 file_get_contents() 和一些 jquery,但我似乎无法使用 jQuery 在 DOM 中找到选择器。

我正在尝试逐行获取它们,因为我打算将它们插入我的数据库以供将来使用。

我的问题是如何获取网页表格中每个 <tr> 中每个 <td> 的值,以便将所有这些值插入到我的数据库中?

PHP:

控制器

function scqf_stats(){

    $data['stats'] = file_get_contents("http://www.scqf.org.uk/Search%20The%20Database?ssub=&stit=Enter+a+title+or+a+part+of+it&sown=Start+typing+and+select+from+dropdown&sownid=&slev=&scrb=&sk=&submitsp=Search");
    $data['main_content'] = 'alt_test';

    $this->load->view('templates/single_view', $data);

}

查看

<pre>

<script src="<?php echo base_url() ?>js/scrape.js"></script>

<?php print_r($stats); ?>

</pre>

jQuery:

$(document).ready(function() {

function scrape_it(){

    $('#search-database-results').children('tbody').children('tr').each(function (){
        $this = $(this);

        $('tr').children('td').each(function() {

            var text = $('td').text();
            console.log(text);

        });   

    });

}

scrape_it();

});

【问题讨论】:

  • id search-database-results 在哪里?这是您要导入的表的名称吗?
  • 您需要显示 HTML 示例,因为您的代码中的“TR”中有“TR”(这可能不正确)。即.children('tr').children('tr')
  • $('#search-database-results tr td').each(function(){...}) 应该足以在 ID=search-database-results 元素中的所有 TR 中找到所有 TD。
  • @Chitowns24 是的,search-database-results 是表的 ID
  • @TrueBlueAussie 抱歉,这是tbody 第一个

标签: php jquery dom web-scraping file-get-contents


【解决方案1】:

假设您在 id=search-database-results 的元素中有抓取的页面,这应该可以在表中的每个 TR 中找到所有 TD(按顺序):

$(document).ready(function() {
    function scrape_it(){
        $('#search-database-results tr td').each(function() {
            var text = $(this).text();
            console.log(text);
        });
    }
    scrape_it();
});

如果您需要更多/不同,请详细说明。

【讨论】:

  • 抓取的页面不在id="search-database-results"内,但表格元素在&lt;table id="search-database-results" class="tablesorter"&gt;&lt;/div&gt;
  • 只是为了确认这也是跨域
  • 看来函数scrape_it()根本没有触发
  • 1.只要 id="search-database-results" 高于它,选择器就无关紧要。 2. 跨域页面 HTML 请求可能会失败,因此您可能需要通过您的服务器对其进行包装。 3. 可以在 JSFiddle 中放一个示例吗?
  • 我刚刚使用CURL,做同样的工作。感谢您的帮助
猜你喜欢
  • 1970-01-01
  • 2021-07-25
  • 1970-01-01
  • 2014-05-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多