是什么让 python webscrape 输出 unicode?
what makes a python webscrape output unicode?
我正在玩 BeautifulSoup 抓取一个 table 及其内容,我注意到我根据结束方式得到不同的输出 - 如果我直接打印它,我会得到一个没有 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() 或索引这样的简单方法来限制行输出的数量?)
但是当我用括号括起最后一行时,
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')
这是怎么回事?提前致谢。
实际上,您的所有输出都是 unicode。 Beautifulsoup默认根据其doc转换成unicode。
当您使用括号和 output
时,您也在打印 tuple
对象。并且在直接执行时只使用 uncode。
它是对象的 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
版本允许查看字符串中不可打印的字符,或者可能无法在当前终端上表示的字符。
当您使用带括号的打印时,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
我正在玩 BeautifulSoup 抓取一个 table 及其内容,我注意到我根据结束方式得到不同的输出 - 如果我直接打印它,我会得到一个没有 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() 或索引这样的简单方法来限制行输出的数量?)
但是当我用括号括起最后一行时,
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')
这是怎么回事?提前致谢。
实际上,您的所有输出都是 unicode。 Beautifulsoup默认根据其doc转换成unicode。
当您使用括号和 output
时,您也在打印 tuple
对象。并且在直接执行时只使用 uncode。
它是对象的 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
版本允许查看字符串中不可打印的字符,或者可能无法在当前终端上表示的字符。
当您使用带括号的打印时,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