【问题标题】:Scraperwiki - python - skipping a table rowScraperwiki - python - 跳过表格行
【发布时间】:2014-07-03 04:19:16
【问题描述】:

我正在尝试抓取一个使用 TH 作为前导列元素并带有以下 TD 标记的表。问题是表格使用了需要跳过的间歇性分隔符,因为它们不包含 TH 标记。

这是表格中的一个示例:

<tr><th scope="row">Availability (non-CRS):</th><td></td></tr>
<tr><td colspan="2" class="fieldDivider"><div>&nbsp;</div></td></tr>
<tr><th scope="row">Start Date:</th><td>01 Jun 2012</td></tr>
<tr><th scope="row">Expiry Date:</th><td>31 May 2015</td></tr>
<tr><th scope="row">Duration:</th><td>36 months</td></tr>
<tr><td colspan="2" class="fieldDivider"><div>&nbsp;</div></td></tr>
<tr><th scope="row">Total Value:</th><td>&pound;18,720,000<i>(estimated)</i></td></tr>

我在 scraperwiki 中使用 python 来收集数据,但在跳过违规行时遇到问题。

在没有任何条件的情况下,一旦我到达没有 TH 标记的行,我的代码就会停止,所以我目前正在使用 if 语句来确保我只在没有不间断空格的行上执行抓取,但我的变量(数据)没有被定义,所以 if 语句没有正确执行。

这是我在教程之外的第一次编码,所以我希望答案很简单,我只是不确定它是什么。

#!/usr/bin/env python

import scraperwiki
import requests
from bs4 import BeautifulSoup

base_url = 'http://www.londoncontractsregister.co.uk/public_crs/contracts/contract-048024/'

html = requests.get(base_url)
soup = BeautifulSoup(html.content, "html.parser")

table = soup.findAll('table')
rows = table[0].findAll('tr')


for row in rows:
    th_cell = row.findAll('th')
    td_cell = row.findAll('td')
    if td_cell[0].get_text() == '&nbsp;':
        data = {
           'description' : th_cell[0].get_text(),
           'record' : td_cell[0].get_text()
        }

print data

【问题讨论】:

  • +1 用于使用requests,比 urllib2 好太多了!

标签: python-2.7 web-scraping scraperwiki


【解决方案1】:

有点快速破解(可能有更好的方法),但这是基于您的代码,似乎得到了我认为您想要的;如果不能,请尝试获取数据并处理异常:

data = []

for row in rows:
    th_cell = row.findAll('th')
    td_cell = row.findAll('td')
    try:
        data.append({'description': th_cell[0].get_text(),
                     'record' : td_cell[0].get_text()})
    except IndexError:
        pass

for item in data:
    print data

【讨论】:

    猜你喜欢
    • 2010-12-02
    • 1970-01-01
    • 2014-11-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-13
    • 2011-07-02
    相关资源
    最近更新 更多