【问题标题】:Using beautifulsoup, how to scrape the table headers from a page使用beautifulsoup,如何从页面中刮取表头
【发布时间】:2014-03-08 01:17:20
【问题描述】:

我尝试使用不同的代码片段来使用 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

我想提取的信息是“data-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

【问题讨论】:

  • 你能告诉我tx在这种情况下代表什么吗?谢谢

标签: python html web-scraping beautifulsoup


【解决方案1】:

从属性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']

【讨论】:

  • 嘿伙计 - 感谢您的快速响应 - 我仍然看到相同的空列表。
  • 嗯,它对我有用。我在上面使用了你的 html 代码(只是在最后添加了&lt;/th&gt;&lt;/tr&gt;&lt;/thead&gt;&lt;/table&gt;)。你用的是什么版本的python/beautifulsoup?你如何初始化soup
  • 目前使用python 2.7.6,bs4。我将汤设置为返回 html 代码的方法。获取链接时使用 for 循环可以正常工作......但不能用于“data-colname”属性。
  • 很奇怪。无论如何,我添加了上面使用的代码。祝你好运。
【解决方案2】:

我认为从get() 中删除th 应该可以解决您的问题。

由于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'))

希望这会有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-10-27
    • 1970-01-01
    • 1970-01-01
    • 2018-12-05
    • 2021-10-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多