从URL抓取文本并在pi上显示

时间:2014-07-24 19:44:57

标签: python raspberry-pi

我从网络服务器上获取文字并尝试在我的覆盆子pi屏幕上显示当前歌曲。使用LCD 16x2

#!/usr/bin/python
# Example using a character LCD connected to a Raspberry Pi or BeagleBone Black.
import math
import time
import urllib2
from BeautifulSoup import BeautifulSoup


import Adafruit_CharLCD as LCD


page = urllib2.urlopen('http://192.168.0.99:9000/status.html').read()
soup = BeautifulSoup(page)
soup.prettify()
mysong = soup.findAll('div', attrs={'class':'playingSong'}) 
# Print a two line message
lcd.message(mysong)

我已经从上面取出了所有的LCD内容,因为它工作正常,但是不正确。我试图获得的HTML元素是:

 <div class="playingSong"><a href="/songinfo.html?item=683&amp;player=00%3A22%3A19%3A0a%3Af2%3A9f" target="browser">Beetlebum</a>

我收到错误:

pi@raspberrypi ~/Adafruit_Python_CharLCD/examples $ sudo python tom.py          Traceback (most recent call last):
  File "tom.py", line 46, in <module>
    lcd.message(mysong)
  File "build/bdist.linux-armv6l/egg/Adafruit_CharLCD/Adafruit_CharLCD.py", line 247, in message
TypeError: ord() expected string of length 1, but Tag found

1 个答案:

答案 0 :(得分:0)

您正在将BeautifulSoup.ResultSet(包含Tag个对象)传递给lcd.message()。相反,您需要首先从结果集中获取元素,然后获取元素的文本:

text = mysong[0].getText()
lcd.message(text)

如果您知道只希望匹配一个元素,请使用find代替findAll

mysong = soup.find('div', attrs={'class':'playingSong'})
text = mysong.getText()
lcd.message(text)