import urllib.request
import re
import os
class hotgame():
def __init__(self):
self.url = "http://top.baidu.com/buzz?b=173&c=16&fr=topcategory_c16" #初始化的url
def send(self,url):
res = urllib.request.urlopen(url)
web = res.read().decode("gb2312")
pat = re.compile(r'<a class="list-title" target="_blank" href=".*?">(.*?)</a>')
res1 = re.findall(pat, web)
if os.path.exists("热门游戏.txt"): #这里是判断是否存在此文件,存在的话删掉
os.remove("热门游戏.txt")
for i in res1:
self.write_f(i)
else:
for i in res1:
self.write_f(i)
def write_f(self,content): #写入文件功能
with open("热门游戏.txt", "a", encoding="utf-8") as f:
f.write(content + "\n")
def start(self):
self.send(self.url)
if __name__ == '__main__': #当py文件运行时候,这个下面的代码将被运行
download =hotgame()
download.start()
提取数据来源百度搜索风云榜上的游戏排行。欢迎各位大神进行指点优化。初学Python,没有系统的去看完整的教程,主要学习方法就是按照其他书中或者视频中的思路去完成自己想到的功能。分析和理解其他人的实例代码。