我在我的 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 版本有关。你可以尝试 Scrapy,使用 HtmlXPathSelector 你应该能够让它工作 [Scrapy works on Python2.7],我已经让 Scrapy 在 RPi 上工作所以我可以保证它会工作。
关于python - BeautifulSoup4 在 Ubuntu 上正常运行,但在 Raspbian 上运行不正常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30023244/