Skip to main content
 首页 » 编程设计

python之使用 BeautifulSoup 时出错

2025年05月04日13xiaohuochai

我想从网站中提取一些数据。我将其保存为“网页,仅限 HTML”,保存在桌面上名为 soccerway.html 的文件中。

之后我使用 IPython notebook 编写了以下命令:

from bs4 import BeautifulSoup 
soup=BeautifulSoup(open("soccerway.html")) 

我收到以下错误:

IOError: [Errno 2] No such file or directory: 'soccerway.html' 

我该如何解决这个问题?

请您参考如下方法:

您不需要手动保存页面。使用 urllib2获取您需要的 html 源代码:

from bs4 import BeautifulSoup 
from urllib2 import urlopen 
 
soup = BeautifulSoup(urlopen("http://my_site.com/mypage")) 

例子:

>>> from bs4 import BeautifulSoup 
>>> from urllib2 import urlopen 
>>> soup = BeautifulSoup(urlopen('http://google.com')) 
>>> soup('a') 
[<a class="gb1" href="http://www.google.com/imghp?hl=en&amp;tab=wi">Images</a>,  
 ... 
]