我正在使用 BeautifulSoup4 抓取网站。这是我所拥有内容的浓缩版:
from bs4 import BeautifulSoup
def getTeamRoster(teamURL):
soup = BeautifulSoup(open(teamURL))
def main():
getTeamRoster("http://modules.ussquash.com/ssm/pages/leagues/Team_Information.asp?id=11325")
我已调出该页面并在我的浏览器 (Chrome) 中正常加载。出于某种原因,我收到以下错误:
Traceback (most recent call last):
File "SquashScraper.py", line 61, in <module>
main()
File "SquashScraper.py", line 58, in main
getTeamRoster("http://modules.ussquash.com/ssm/pages/leagues/Team_Information.asp?id=11325")
File "SquashScraper.py", line 21, in getTeamRoster
soup = BeautifulSoup(open(teamURL))
FileNotFoundError: [Errno 2] No such file or directory: 'http://modules.ussquash.com/ssm/pages/leagues/Team_Information.asp?id=11325'
知道会发生什么吗?
我看过其他人的 BeautifulSoup4 代码,认为我所做的是访问页面 HTML 的惯用方式。
谢谢, 布莱曼
请您参考如下方法:
BeautifulSoup 在描述中提到它是一个用于解析 的库,而不是一个实际从远程网站获取 HTML 的库。为此,您将需要另一个库,例如 urllib(特别是函数 urlopen,然后从它返回的对象中read)。
至于为什么会出现 Python 错误,open 是为打开文件而设计的,而不是为 HTML 检索而设计的。如果您要打开一个包含 HTML 的本地文件,您的代码将起作用。但是,因为您有一个 URL 作为参数,所以 open 实际上是在您的系统上查找具有该名称的文件。因为该文件不存在,所以会引发错误。
