我想我必须使用 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'))
请您参考如下方法:
您的问题没有简短的答案。我将向您展示一个完整的解决方案并注释这段代码。
首先,导入必要的模块:
from bs4 import BeautifulSoup
import requests
import re
接下来,获取索引页面并创建 BeautifulSoup 对象:
req = requests.get("http://www.chessgames.com/perl/chesscollection?cid=1014492")
soup = BeautifulSoup(req.text, "lxml")
我强烈建议使用lxml 解析器,而不是常见的html.parser 之后,您应该准备游戏的链接列表:
pages = soup.findAll('a', href=re.compile('.*chessgame\?.*'))
您可以通过搜索包含“chessgame”字样的链接来实现。 现在,您应该准备为您下载文件的函数:
def download_file(url):
path = url.split('/')[-1].split('?')[0]
r = requests.get(url, stream=True)
if r.status_code == 200:
with open(path, 'wb') as f:
for chunk in r:
f.write(chunk)
最后的魔法是重复之前的所有步骤,为文件下载器准备链接:
host = 'http://www.chessgames.com'
for page in pages:
url = host + page.get('href')
req = requests.get(url)
soup = BeautifulSoup(req.text, "lxml")
file_link = soup.find('a',text=re.compile('.*download.*'))
file_url = host + file_link.get('href')
download_file(file_url)
(首先搜索描述中包含文本“下载”的链接,然后构造完整的 url - 连接主机名和路径,最后下载文件)
我希望你能不加修改地使用这段代码!
