使用beautifulsoup,如何从一个页面刮去表头

问题描述 投票:0回答:2

我使用的代码不同的片刮使用BS和python,每次我只是得到返回一个空表的表头的名字尝试。这是我想提取的值:

<table class="table table-bordered table-striped table-hover data-grid ng-scope">
    <thead>
       <tr>
          <th class="ng-isolate-scope sortable" data-colname="Advertiser" data-colsorter="sorter">
           Advertiser

我想提取的信息是“数据-colname的”。这是我已经试过:

for tx in soup.find_all('th'):
    table_headers.append(tx.get('th.data-colname'))
#this returns an empty list, tried other combinations of this sort ... all returned an empty list

#Another attempt was:
spans = [x.text.strip() for x in soup.select('th.ng-isolate-scope data-colname')]
# returns errors
python html web-scraping beautifulsoup
2个回答
1
投票

我觉得从th应该可以解决你的问题里面取出get()

由于tx它已经:

<th class="ng-isolate-scope sortable" data-colname="Advertiser" data-colsorter="sorter">
           Advertiser

或者它的兄弟姐妹,你只需要你处理一次一个元素。所以,长话短说:

for tx in soup.find_all('th'):
    table_headers.append(tx.get('data-colname'))

希望这可以帮助。


0
投票

提取从属性data-colname值正确的方法是用,例如:

    for tx in soup.find_all('th'):
        table_headers.append(tx['data-colname'])

下面是我使用的代码:

    from bs4 import BeautifulSoup
    html = '<table class="table table-bordered table-striped table-hover data-grid ng-scope"> <thead><tr><th class="ng-isolate-scope sortable" data-colname="Advertiser" data-colsorter="sorter">Advertiser</th></tr></thead></table'
    soup = BeautifulSoup(html, 'lxml')
    table_headers = []
    for tx in soup.find_all('th'):
        table_headers.append(tx['data-colname'])

输出:

    >>> print table_headers
    [u'Advertiser']
© www.soinside.com 2019 - 2024. All rights reserved.