【问题标题】:BeautifulSoup 'href' list that is giving ambiguous TypeErrors?BeautifulSoup 'href' 列表给出了模棱两可的 TypeErrors?
【发布时间】:2013-03-18 09:18:30
【问题描述】:

我正在使用 beautifulsoup 从网页中抓取网址。一切都很顺利,直到某些 url 中包含非 ascii 字符。

requests.get('http://www.reddit.com')
soup = BeautifulSoup(req.content)

urls = [i.get('href') for i in soup.findAll('a') if
        'keyword' in str(i.get('href'))]

列表解析将返回UnicodeError
所以我想把这个列表理解分成两部分:

urls = [i.get('href') for i in soup.findAll('a')]

urls = [i.encode('utf-8') for i in urls]

这时我收到了AttributeError,说这些项目是NoneType

我检查了他们的类型:

print [type(i) for i in urls]

其中显示了所有 unicode 类型。好像说他们同时是Noneunicode

【问题讨论】:

    标签: python unicode types beautifulsoup


    【解决方案1】:

    您一定错过了None 值。我查了www.reddit.com,果然有:

    <a name="content"></a>
    

    它的href是None。您可以执行以下操作,而不是打印所有值并手动搜索 None

    urls = [(i, i.get('href')) for i in soup.findAll('a')]
    print [u for u in urls if u[1] is None]
    

    【讨论】:

    • 我在列表中看到了“#content”,但是当我检查类型时,它仍然显示unicode。谢谢,我会试试这个。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-02-13
    • 2014-08-12
    • 1970-01-01
    • 2020-09-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多