正则表达式练习
- 工具
- 目的
- 代码
- 运行结果
工具
pycharm
目的
'''
https://www.77xsw.cc/fenlei/1_1/:第一页的网址
https://www.77xsw.cc/fenlei/1_2/:第二页的网址
...
https://www.77xsw.cc/fenlei/1_10/:第十页的网址
'''
代码
import requests
import re
import jsonnovel_list = []for i in range(1,11):# 请求网址url = 'https://www.77xsw.cc/fenlei/1_' + str(i) + '/'headers = {'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36'}# 发送请求response = requests.get(url, headers=headers)# print(response.text)# 数据处理 确定正则表达式规则时,看抓取到的没有美化的响应结果data = response.text# 用中文不能匹配中文的标点符号# rule = '<span class="sp_2"><a href="(.*?)".*?title="[\u4e00-\u9fa5]*">([\u4e00-\u9fa5]*?)</a></span><span class="sp_3">' # not# rule = '<span class="sp_2"><a href="(.*?)".*?title=".*?">(.*?)</a></span><span class="sp_3">' # okrule = '<span class="sp_2"><a href="(.*?)".*?>(.*?)</a></span><span class="sp_3">'result = re.findall(rule,data) # 返回值为多个匹配结果组成的列表for novel in result:novel_list.extend(result)# print(novel_list)
novel_tuple = tuple(novel_list) # 去重
novel_dict = dict([i[1], i[0]] for i in novel_tuple) # 转为字典
print(novel_dict,len(novel_dict)) # 一页40个,10页应该有400个,结果为397个,含有重复的
# 保存数据 json格式
with open('novel.json', 'w', encoding='utf8') as f:json.dump(novel_dict,f,indent=2,ensure_ascii=False)
运行结果
见资源