Python爬取知乎网站代码
时间: 2024-07-14 11:00:55 浏览: 289
Python爬取知乎图片代码实现解析
Python爬取知乎网站通常涉及网络请求库如`requests`和解析HTML内容的库如`BeautifulSoup`或`lxml`。以下是一个简单的示例,展示如何用Python爬取知乎文章标题:
```python
import requests
from bs4 import BeautifulSoup
# 定义目标URL
url = "https://www.zhihu.com/topic/19550876/top-answers"
# 发送GET请求获取网页内容
response = requests.get(url)
# 检查请求是否成功
if response.status_code == 200:
# 解析HTML
soup = BeautifulSoup(response.text, 'html.parser')
# 找到包含文章标题的部分(这里假设是h2标签)
article_titles = soup.find_all('h2', class_='QuestionItem-title')
for title in article_titles:
print(title.get_text()) # 输出文章标题
else:
print("请求失败,状态码:", response.status_code)
阅读全文