【问题标题】:Grabbing text from URL and showing on pi从 URL 抓取文本并在 pi 上显示
【发布时间】:2014-07-25 03:53:04
【问题描述】:

我正在从网络服务器获取文本并尝试通过 python 在我的树莓派屏幕上显示当前歌曲。使用 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 东西都去掉了,但是 mysong 没有设置正确。我要获取的 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

【问题讨论】:

    标签: python raspberry-pi


    【解决方案1】:

    您将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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-03-27
      • 2012-07-12
      • 1970-01-01
      • 2015-08-10
      • 1970-01-01
      • 1970-01-01
      • 2017-01-05
      • 1970-01-01
      相关资源
      最近更新 更多