请帮我写出用python爬取知乎帖子的具体代码
时间: 2023-09-14 13:12:38 浏览: 175
好的,以下是爬取知乎帖子的Python代码:
```python
import requests
from bs4 import BeautifulSoup
url = 'https://www.zhihu.com/question/123456789' # 将链接替换成你要爬取的知乎帖子链接
# 使用requests库获取网页内容
response = requests.get(url)
html = response.content
# 使用BeautifulSoup库解析网页内容
soup = BeautifulSoup(html, 'html.parser')
# 获取帖子标题和内容
title = soup.find('h1', class_="QuestionHeader-title").text.strip()
content = soup.find('div', class_="QuestionHeader-detail").text.strip()
# 打印帖子标题和内容
print('Title:', title)
print('Content:', content)
# 获取帖子回答
answers = soup.find_all('div', class_="List-item")
# 遍历回答并打印
for answer in answers:
author = answer.find('span', class_="UserLink AuthorInfo-name").text.strip()
content = answer.find('div', class_="RichContent-inner").text.strip()
print('Author:', author)
print('Content:', content)
```
请注意,在代码中,你需要将 `url` 替换成你要爬取的知乎帖子链接。此外,为了避免被知乎反爬虫机制封禁,你可能还需要添加一些headers等信息来进行模拟登录等操作。
阅读全文