我有我的Ubuntu服務器15.04 VPS上運行的下面的腳本,它完美的作品。我正在調整它在我的Raspberry Pi(完全更新的Raspbian Wheezy)上運行,但BeautifulSoup4沒有檢測到它在VPS上的頁面元素。代碼和回溯如下。爲什麼這個錯誤發生在我的Pi上,但不在我的VPS上?BeautifulSoup4在Ubuntu上正常工作,但不是Raspbian
這是相關的一段代碼。其中,導入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>
元素,因爲它應該。與soup.prettify()
一樣,打印page.text
確實會返回整頁源代碼。