python爬虫爬取百度百科内容并将结果保存至word文档
时间: 2023-10-15 19:04:33 浏览: 78
以下是一个简单的Python爬虫程序,用于爬取百度百科内容,并将结果保存到Word文档中:
```python
import requests
from bs4 import BeautifulSoup
from docx import Document
def get_content(url):
res = requests.get(url)
soup = BeautifulSoup(res.text, 'html.parser')
content = soup.find('div', {'class': 'lemma-summary'}).get_text().strip()
return content
def save_to_word(title, content):
doc = Document()
doc.add_heading(title, 0)
doc.add_paragraph(content)
doc.save(title + '.docx')
if __name__ == '__main__':
url = 'https://baike.baidu.com/item/Python/407313'
title = 'Python百度百科'
content = get_content(url)
save_to_word(title, content)
```
该程序首先使用requests库获取指定百度百科页面的HTML内容,然后使用BeautifulSoup库解析HTML并获取页面摘要的内容。最后,使用python-docx库将结果保存到Word文档中。
使用该程序时,只需将URL、标题和保存的文件名更改为所需的内容即可。