运用正则表达式极简代码爬取古诗信息(主要是练习正则表达式,很多后续的功并没有实现)
我们先看一下结果:注:只是截取了一部分结果
我们直接上代码:
import re
import requests
def parse_url(url):
headers={'User-Agent':
'此处需要替换成你本机的'
}
reponse = requests.get(url, headers= headers)
text = reponse.text
# print(text)
titles = re.findall(r'<div\sclass="cont">.*?<b>(.*?)</b>',text,re.DOTALL)
# print(titles)
authors = re.findall(r'<p\sclass="source">.*?<a .*?>(.*?)</a>',text,re.DOTALL)
# print(authors)
dynasties = re.findall(r'<p\sclass="source">.*?<a .*?>.*?<a .*?>(.*?)</a>',text,re.DOTALL)
# print(dynasties)
contents = re.findall(r'<div\sclass="contson".*?>(.*?)</div>',text,re.DOTALL)
# print(contents)
All_contents=[] # 定义一个空列表
for i in contents:
content = re.sub(r'<.*?>', " ", i)
All_contents.append(content.strip())
# print(All_contents)
poems=[] # 定义一个空列表
for value in zip(titles, authors, dynasties, All_contents):# 将这四个列表中的每一项分别一一对应
title,author,dynasty,content = value # 将value里面的每一项赋予名字
poem={
'title':title,
'author':author,
'dynasty':dynasty,
'content':content
}
poems.append(poem) # 将poem追加到poems中
print(poems)
def main():
for i in range(1,5):
url = 'https://www.gushiwen.cn/default_{}.aspx'.format(i)
parse_url(url)
if __name__ == '__main__':
main()
注:中间代码没有问题哦!