【问题标题】:what makes a python webscrape output unicode?是什么让 python webscrape 输出 unicode?
【发布时间】:2015-05-19 02:17:34
【问题描述】:

我正在使用 BeautifulSoup 抓取表格及其内容,我注意到根据我结束它的方式我得到不同的输出 - 如果我直接打印它,我得到一个没有 unicode 表示法的输出。

html = urlopen('http://www.bcsfootball.org').read()
soup = BeautifulSoup(html)

for row in soup('table', {'class':'mod-data'})[0].tbody('tr'):
    tds = row('td')
    print tds[0].string, tds[1].string

给予:

1 Florida State
2 Auburn
3 Alabama
4 Michigan State
5 Stanford

等等(顺便说一句,有没有像 .head() 或 index 这样的简单方法来限制行输出的数量?)

但是当我将最后一行放在括号中时,

print (tds[0].string, tds[1].string)

或者给行赋值一个变量然后打印变量,

output = tds[0].string, tds[1].string
print output

我得到了 unicode 的输出:

(u'1', u'Florida State')
(u'2', u'Auburn')
(u'3', u'Alabama')
(u'4', u'Michigan State')
(u'5', u'Stanford')

这里发生了什么?提前致谢。

【问题讨论】:

    标签: python unicode beautifulsoup


    【解决方案1】:

    这是对象的repr() 输出与其str() 输出之间的差异。我还注意到您使用的是 Python 2.X,其中 print 是关键字:

    >>> s=u'M\xfcrk'
    >>> print s        # Formatted for output display
    Mürk
    >>> print repr(s)  # Formatted to view type and content
    u'M\xfcrk'
    >>> s              # It is what you get by default at interactive prompt
    u'M\xfcrk'
    

    注意repr 版本可以查看字符串中的不可打印字符,或者当前终端上可能无法表示的字符。

    当您使用带括号的 print 时,Python 2.X 认为您正在打印 tuple。显示列表、元组等序列时,默认显示repr版本的字符串:

    >>> print (s)       # NOT a tuple, so seems to work
    Mürk
    >>> print (s,)      # A 1-tuple
    (u'M\xfcrk',)
    >>> print (s,1,2)   # A 3-tuple
    (u'M\xfcrk', 1, 2)
    >>> print s,1,2     # prints normally.
    Mürk 1 2
    

    【讨论】:

    • 哦,是的……我以前见过这些东西,哈哈。谢谢好心的先生
    【解决方案2】:

    实际上,您的所有输出都是 unicode。 Beautifulsoup 默认根据其doc 转换为 unicode。

    当您使用括号和output 时,您也在打印tuple 对象。直接使用时只使用 uncode。

    【讨论】:

      猜你喜欢
      • 2016-08-19
      • 1970-01-01
      • 2020-04-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-09
      • 2020-07-18
      相关资源
      最近更新 更多