![Ubuntu 14.04 上使用 Python 2.7.6 运行 BeautifulSoup4](https://linux22.com/image/867041/Ubuntu%2014.04%20%E4%B8%8A%E4%BD%BF%E7%94%A8%20Python%202.7.6%20%E8%BF%90%E8%A1%8C%20BeautifulSoup4.png)
我已经使用安装了 bs4
apt-get install python-bs4
当我尝试运行脚本时:
import urllib2
import bs4
url = "http://rads.stackoverflow.com/amzn/click/B007C9N4H8"
web_page = urllib2.urlopen(url)
page_text = web_page.read()
soup = bs4.BeautifulSoup(page_text)
print soup.title.string`
我收到此错误:
Traceback (most recent call last):
File "./bs4.py", line 4, in <module>
import bs4
File "/home/pbmac/tmp/bs4.py", line 8, in <module>
soup = bs4.BeautifulSoup(page_text)
AttributeError: 'module' object has no attribute 'BeautifulSoup'
然而-当我直接从 python 内部运行它时:
Python 2.7.6 (default, Mar 22 2014, 22:59:56)
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import urllib2
>>> import bs4
>>> url = "http://rads.stackoverflow.com/amzn/click/B007C9N4H8"
>>> web_page = urllib2.urlopen(url)
>>> page_text = web_page.read()
>>> soup = bs4.BeautifulSoup(page_text)
>>> print soup.title.string
Amazon.com: The Muppets (2011): Jason Segel, Amy Adams, Chris Cooper, Rashida Jones: Amazon Instant Video
这才是正确答案。
为什么它直接从 python 运行 - 但不是作为单独的文件运行?
谢谢pat
答案1
您将文件命名为bs4.py
。因此 Python 会导入该文件而不是模块,bs4
并抛出错误,因为您的文件不包含任何名为 的内容BeautifulSoup
。
对您的文件使用其他名称。