【问题标题】:extracting child href to BeautifulSoup list将子 href 提取到 BeautifulSoup 列表
【发布时间】:2012-12-24 14:48:06
【问题描述】:

我正在学习 python 并使用 BeautifulSoup 来抓取一些网页。我要做的是找到第一个'td'的子'a',提取href并将其添加到列表中。如何以及在何处将 href 添加到单元格文本?

import urllib2

from BeautifulSoup import BeautifulSoup

def listify(table):
    """Convert an html table to a nested list""" 
    result = []
    rows = table.findAll('tr')
    for row in rows:
        result.append([])
        cols = row.findAll('td')
        for col in cols:
            strings = [_string.encode('utf8') for _string in col.findAll(text=True)]
            text = ''.join(strings)
            result[-1].append(text)
    return result

【问题讨论】:

  • cols[1].find('a')['href'] 应该可以解决问题
  • 有什么理由不使用 BeautifulSoup 4 而不是 3?
  • 对 bs4 的好评。我都下载了,但安装了 3。现在使用 4。

标签: python beautifulsoup href urllib2


【解决方案1】:
  • 找到第一个td:改用row.find('td');它将返回第一个匹配项
  • 查找子a,再次使用.find('a') 查找第一个。
  • 元素的行为类似于 python dict,使用项目访问来获取元素属性,例如 href

合起来就是:

cell = row.find('td')
link = cell.find('a') if cell else None
if link is not None and 'href' in link:
    result[-1].append(link['href'])

【讨论】:

    猜你喜欢
    • 2015-02-27
    • 2017-11-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-10
    相关资源
    最近更新 更多