简介:
Python 是一门简单易学且功能强大的编程语言,无需繁琐的配置,掌握基本语法,了解基本库函数,就可以通过调用海量的现有工具包编写自己的程序,轻松实现批量自动化操作,可以极大提高办公和学习效率。Python爬虫可以批量获取网页上的数据。
1. 代码编辑器 Pycharm community
2. 代码解释器 Python 3.7.6
3. 在Pycharm中创建项目并配置Python环境
4. 安装工具包的两种方式
1、爬虫的基本步骤
2、4399小游戏的本地运行
游戏绝对地址示例: http://sxiao.4399.com/4399swf/upload_swf/ftp29/liuxinyu/20190731/7/main.swf
游戏相对地址示例: /upload_swf/ftp29/liuxinyu/20190731/7/main.swf
3、4399小游戏爬虫实现思路
完整代码
1import os
2import re
3import threading
4
5from bs4 import BeautifulSoup as bs
6import requests
7
8
9def getAllGameUrl():
10 """
11 获取所有游戏的名称和游戏信息页的链接
12 :return:
13 """
14 gameUrlList = []
15 response = requests.get(‘http://www.4399.com/flash/gamehw.htm‘)
16 dom = bs(response.content, ‘html.parser‘)
17 gameLiList = dom.select(‘#skinbody > div:nth-child(6) > ul > li‘)
18 for i in gameLiList:
19 # 获取游戏的名称
20 gameName = i.select_one(‘a > b‘).get_text()
21 # 获取游戏信息页的链接
22 # ‘http://www.4399.com/flash/212103.htm‘
23 gameInfoUrl = indexUrl + i.select_one(‘a‘)[‘href‘]
24 gameUrlList.append({‘gameName‘: gameName, ‘gameInfoUrl‘: gameInfoUrl})
25 return gameUrlList
26
27
28def downloadIfAvailable(game):
29 """
30 判断一个游戏是否支持本地下载
31 :return:
32 """
33 response = requests.get(game[‘gameInfoUrl‘])
34 plainText = response.text
35 relativeUrlList = re.findall(r‘(?<=_strGamePath=").+?\.swf‘, plainText)
36 if len(relativeUrlList) != 0:
37 gameUrl = gameBaseUrl + relativeUrlList[0]
38 game[‘gameUrl‘] = gameUrl
39 threading.Thread(target=downloadAGame, args=(game,)).start()
40
41
42def downloadAGame(game):
43 """
44 根据下载链接下载游戏,并保存到.swf文件
45 :param game:
46 :return:
47 """
48 downloadPath = ‘games/‘
49 if not os.path.exists(downloadPath):
50 try:
51 os.mkdir(downloadPath)
52 except FileExistsError as e:
53 print(e)
54 with open(downloadPath + game[‘gameName‘] + ‘.swf‘, ‘wb‘) as file:
55 file.write(requests.get(game[‘gameUrl‘]).content)
56 print(game[‘gameName‘] + ‘下载完成‘)
57
58
59if __name__ == ‘__main__‘:
60 indexUrl = ‘http://www.4399.com‘
61 gameBaseUrl = ‘http://sxiao.4399.com/4399swf‘
62 gameUrlList = getAllGameUrl()
63 for i in gameUrlList:
64 threading.Thread(target=downloadIfAvailable, args=(i,)).start()
如何用Python爬取小游戏网站,把喜欢的游戏收藏起来(附源码)
原文:https://www.cnblogs.com/python0921/p/12869725.html