BeautifulSoup4适用于Ubuntu但不适用于Raspbian

时间:2015-05-04 05:39:14

标签: python linux beautifulsoup raspberry-pi raspbian

我在Ubuntu Server 15.04 VPS上运行以下脚本,它运行正常。我正在调整它以在我的Raspberry Pi(完全更新的Raspbian Wheezy)上运行,但是BeautifulSoup4没有像在VPS上那样检测页面元素。代码和回溯如下。为什么这个错误发生在我的Pi上,而不是发生在我的VPS上?

这是相关的代码段。除此之外,还会导入osBeautifulSoupfrom bs4)和requests。第5行和第5行在循环内部(实际脚本循环遍历字典以检查所有设备);我已经验证了a)下面的命令是实际运行的,以及b)运行完全相同的代码在VPS上工作(返回数据)但不在Pi上(抛出错误)。

page = requests.get('https://developers.google.com/android/nexus/images')
soup = BeautifulSoup(page.text)

# loop starts here
cur = "/var/www/nexus_temp/shamu.html"
try:
    os.remove(cur)
except OSError:
    pass

g = open(cur, 'wb')
data = str(soup.select("h2#shamu ~ table")[0])
g.write(data)
g.close()

回溯:

Traceback (most recent call last):
  File "./nimages.py", line 40, in <module>
    data = str(soup.select("h2#shamu ~ table")[0])
IndexError: list index out of range

从Python命令行运行脚本并执行print soup.select("h2#shamu ~ table")只返回[],但print soup.find_all('h2')会返回页面上的所有<h2>元素。打印page.text会返回整页源代码,soup.prettify()也是如此。

1 个答案:

答案 0 :(得分:0)

关于所使用的Python版本,它可能是版本问题。您可以尝试Scrapy,使用HtmlXPathSelector,你应该能够使它工作[Scrapy适用于Python2.7],我已经让Scrapy在RPi上工作,所以我可以保证它会起作用。