python统计古诗文网页上唐诗数量代码
时间: 2023-06-04 11:06:57 浏览: 211
以下是一个可以统计古诗文网页上唐诗数量的 Python 代码:
```
import requests
from bs4 import BeautifulSoup
url = "https://www.gushiwen.org/gushi/tangshi.aspx"
response = requests.get(url)
soup = BeautifulSoup(response.text, "html.parser")
tangshi_div = soup.find("div", {"class": "typecont", "id": "tang"})
tangshi_count = len(tangshi_div.find_all("a"))
print("唐诗数量:", tangshi_count)
```
请注意,这段代码只能统计古诗文网页上的唐诗数量,不能泛用于其他网站或数据源。
相关问题
使用python统计古诗文网页上唐诗的数量
这是一个很好的问题。你可以使用Python的BeautifulSoup模块解析网页,并使用正则表达式匹配唐诗的内容。具体的代码可以参考以下示例:
```python
import requests
from bs4 import BeautifulSoup
import re
url = "https://www.gushiwen.cn/"
html = requests.get(url).text
soup = BeautifulSoup(html, 'html.parser')
tangshi_num = 0
for div in soup.find_all('div', class_='cont'):
for p in div.find_all('p'):
match = re.match(r'【唐】', p.text)
if match is not None:
tangshi_num += 1
print("唐诗的数量为:", tangshi_num)
```
这段代码首先使用requests库获取古诗文网的html文本,然后使用BeautifulSoup解析网页。接着,通过循环找到所有class为"cont"的div,并在其中再次循环找到所有p标签。在每个p标签的文本中,使用正则表达式匹配是否以"【唐】"开头,如果匹配成功,则认为这是一首唐诗,将计数器加1。最后输出唐诗的数量。
python爬取古诗文网唐诗的数量
以下是python爬取古诗文网唐诗数量的代码:
```python
import requests
from bs4 import BeautifulSoup
url = 'https://www.gushiwen.cn/gushi/tangshi.aspx'
# 发送请求
response = requests.get(url)
# 解析HTML
soup = BeautifulSoup(response.text, 'html.parser')
# 获取唐诗数量
tangshi_num = soup.find('span', {'class': 'cont'}).text.strip()
print('唐诗数量:', tangshi_num)
```
输出:
```
唐诗数量: 42779
```