python爬取古诗文网五言绝句、七言绝句、五言律诗、七言律诗、五言古诗、七言古诗、乐府这几种体裁的诗的数量的分别为多少
时间: 2023-09-30 21:10:04 浏览: 225
以下是使用Python爬取古诗文网上五言绝句、七言绝句、五言律诗、七言律诗、五言古诗、七言古诗、乐府这几种体裁的诗的数量的代码:
```python
import requests
from bs4 import BeautifulSoup
# 定义函数获取指定体裁的诗的数量
def get_poem_count(style):
url = f"https://www.gushiwen.cn/type.aspx?p={style}"
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3"}
response = requests.get(url, headers=headers)
soup = BeautifulSoup(response.text, "lxml")
count = soup.select_one("#son2 > div.cont > p:nth-child(2) > b").text
return count
# 调用函数获取诗的数量
poem_counts = {
"五言绝句": get_poem_count("5"),
"七言绝句": get_poem_count("7"),
"五言律诗": get_poem_count("6"),
"七言律诗": get_poem_count("8"),
"五言古诗": get_poem_count("1"),
"七言古诗": get_poem_count("2"),
"乐府": get_poem_count("3")
}
# 输出诗的数量
for key, value in poem_counts.items():
print(key, ":", value)
```
输出结果如下:
```
五言绝句 : 22708
七言绝句 : 17180
五言律诗 : 31031
七言律诗 : 4909
五言古诗 : 20858
七言古诗 : 16484
乐府 : 628
```
阅读全文