【发布时间】:2015-05-04 05:39:13
【问题描述】:
我在我的 Ubuntu Server 15.04 VPS 上运行了以下脚本,它运行良好。我正在调整它以在我的 Raspberry Pi(完全更新的 Raspbian Wheezy)上运行,但 BeautifulSoup4 并没有像在 VPS 上那样检测页面元素。代码和回溯如下。为什么这个错误发生在我的 Pi 而不是我的 VPS?
这是相关的代码。其中,os、BeautifulSoup (from bs4) 和 requests 被导入。第 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() 也是如此。
【问题讨论】:
标签: python linux beautifulsoup raspberry-pi raspbian