我想我必须使用urlopen
打开每个url,然后使用urlretrieve
从每个游戏底部的下载按钮访问每个pgn来下载它。我必须为每个游戏创建一个新的BeautifulSoup
对象吗?我也不确定urlretrieve
是如何工作的。
import urllib
from urllib.request import urlopen, urlretrieve, quote
from bs4 import BeautifulSoup
url = 'http://www.chessgames.com/perl/chesscollection?cid=1014492'
u = urlopen(url)
html = u.read().decode('utf-8')
soup = BeautifulSoup(html, "html.parser")
for link in soup.find_all('a'):
urlopen('http://chessgames.com'+link.get('href'))
你的问题没有简短的答案。我将向您展示一个完整的解决方案并评论此代码。
首先,导入必要的模块:
接下来,获取索引页并创建
BeautifulSoup
对象:我强烈建议使用
lxml
解析器,而不是普通的html.parser
之后,你应该准备游戏的链接列表:你可以通过搜索包含“棋盘游戏”单词的链接来完成。 现在,您应该准备将为您下载文件的函数:
最后一个魔术是重复所有先前的步骤,为文件下载程序准备链接:
(首先搜索描述中包含文本“download”的链接,然后构造完整的url-连接主机名和路径,最后是下载文件)
我希望你可以使用这个代码没有更正!
相关问题 更多 >
编程相关推荐