【问题标题】:BeautifulSoup4 works properly on Ubuntu but not RaspbianBeautifulSoup4 在 Ubuntu 上正常工作,但在 Raspbian 上不能正常工作
【发布时间】: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') 会返回页面上的所有 &lt;h2&gt; 元素,这是应该的。打印page.text 会返回整页源代码,soup.prettify() 也是如此。

【问题讨论】:

    标签: python linux beautifulsoup raspberry-pi raspbian


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2011-12-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-02
      • 2017-12-12
      • 2014-06-23
      • 2012-07-26
      相关资源
      最近更新 更多