python爬虫爬取https://tieba.baidu.com/f?ie=utf-8&kw=%E4%B8%AD%E5%8E%9F%E5%B7%A5%E5%AD%A6%E9%99%A2&fr=search并把数据存储
时间: 2024-06-08 17:06:06 浏览: 23
好的,以下是一个爬取贴吧帖子的示例代码,使用了Requests和BeautifulSoup库:
``` python
import requests
from bs4 import BeautifulSoup
# 设置请求头
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'}
# 发送请求
url = 'https://tieba.baidu.com/f?ie=utf-8&kw=%E4%B8%AD%E5%8E%9F%E5%B7%A5%E5%AD%A6%E9%99%A2&fr=search'
response = requests.get(url, headers=headers)
# 解析网页内容
soup = BeautifulSoup(response.content, 'html.parser')
post_list = soup.find_all('li', class_='j_thread_list clearfix')
# 输出帖子标题和链接
for post in post_list:
title = post.find('a', class_='j_th_tit').get('title')
link = 'https://tieba.baidu.com' + post.find('a', class_='j_th_tit').get('href')
print(title, link)
# 存储数据到文件
with open('tieba_posts.txt', 'w', encoding='utf-8') as f:
for post in post_list:
title = post.find('a', class_='j_th_tit').get('title')
link = 'https://tieba.baidu.com' + post.find('a', class_='j_th_tit').get('href')
f.write(title + '\n' + link + '\n\n')
```
这个示例代码可以爬取中原工学院吧的帖子标题和链接,并将其存储到 tieba_posts.txt 文件中。你可以根据需要修改代码来爬取更多数据或者存储到其他格式的文件中。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)