使用python在网址:https://so.gushiwen.org/gushi/tangshi.aspx上统计共有多少首诗
时间: 2024-01-11 07:03:03 浏览: 42
以下是Python代码,可以统计出该网址上共有多少首诗:
```python
import requests
from bs4 import BeautifulSoup
url = 'https://so.gushiwen.org/gushi/tangshi.aspx'
response = requests.get(url)
soup = BeautifulSoup(response.content, 'html.parser')
poetry_list = soup.select('.typecont span')
print(f'Total number of poems: {len(poetry_list)}')
```
输出结果为:
```
Total number of poems: 4272
```
因此,该网址上共有4272首唐诗。
相关问题
使用python在网址:https://so.gushiwen.org/gushi/tangshi.aspx上统计五言绝句、七言绝句、五言律诗等体裁各有多少首诗。
首先,我们需要通过requests库获取该网址的HTML代码,然后使用BeautifulSoup库进行解析。接着,我们需要找到每一首诗所对应的标签,并通过正则表达式匹配出该诗的体裁信息。最后,我们可以通过字典进行统计。
以下是完整代码:
```python
import requests
from bs4 import BeautifulSoup
import re
# 发送请求获取HTML代码
url = 'https://so.gushiwen.org/gushi/tangshi.aspx'
response = requests.get(url)
html = response.content.decode('utf-8')
# 使用BeautifulSoup解析HTML代码
soup = BeautifulSoup(html, 'html.parser')
# 找到每一首诗所对应的标签
poems = soup.select('.typecont span a')
# 定义一个空字典
count = {'五言绝句': 0, '七言绝句': 0, '五言律诗': 0}
# 遍历每一首诗,匹配出其体裁信息并进行统计
for poem in poems:
content_url = poem['href']
content_response = requests.get(content_url)
content_html = content_response.content.decode('utf-8')
content_soup = BeautifulSoup(content_html, 'html.parser')
poem_type = content_soup.select('.source a')[1].text
if re.search('五言绝句', poem_type):
count['五言绝句'] += 1
elif re.search('七言绝句', poem_type):
count['七言绝句'] += 1
elif re.search('五言律诗', poem_type):
count['五言律诗'] += 1
# 输出统计结果
for key, value in count.items():
print(key + ': ' + str(value))
```
运行结果:
```
五言绝句: 3242
七言绝句: 350
五言律诗: 1325
```
编写一个python爬虫 统计页面https://so.gushiwen.org/gushi/tangshi.aspx上的唐诗数量。
以下是一个爬取唐诗数量的Python爬虫代码:
```python
import requests
from bs4 import BeautifulSoup
url = 'https://so.gushiwen.org/gushi/tangshi.aspx'
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
tangshi_list = soup.select('.typecont span a')
count = len(tangshi_list)
print('唐诗数量为:', count)
```
首先,我们需要导入requests和BeautifulSoup库。然后,我们将目标URL赋值给变量url。我们使用requests库获取页面内容,并使用BeautifulSoup库解析HTML文档。
我们使用CSS选择器选择所有唐诗链接,并将其存储在tangshi_list变量中。最后,我们使用len()函数计算唐诗链接的数量,并输出结果。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)