python爬取股吧评论完整代码
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'}
设置需要爬取的股票代码
stock_code = 'sh600519'
设置需要爬取的页面数
page_num = 2
循环爬取每一页的数据
for page in range(1, page_num + 1): # 构造爬取链接 url = f'http://guba.eastmoney.com/list,{stock_code}_{page}.html' # 发送请求 response = requests.get(url, headers=headers) # 解析页面 soup = BeautifulSoup(response.content, 'lxml') # 获取评论列表 comment_list = soup.find_all('div', class_='articleh normal_post') # 循环输出每条评论 for comment in comment_list: # 获取评论人 user = comment.find('a', class_='author_name').text.strip() # 获取评论内容 content = comment.find('div', class_='articlehContent').text.strip() # 输出评论 print(user + ': ' + content)
其中,爬取的股票代码和页面数可以根据需求进行修改。在爬取时需要注意防止反爬策略,需要设置请求头。同时,也要考虑异常情况的处理,比如网络请求失败的情况。
相关推荐

















