爬虫准备
本次用selenmium和bs4进行爬虫,最后把数据储存进json文件里,需要使用的库有这些。
from selenium import webdriver
from bs4 import BeautifulSoup
from selenium.webdriver.chrome.options import Options
import json
爬虫
先爬取贴子的基本信息,如评论,阅读数,帖子链接等。有些咨询帖子是官方发的,和爬取的股票没有关系,所以需要过滤掉。
def get_list(stock, x, y):
DFCF_dict = {
'view_num': [], 'comment_num': [], 'title': [], 'poster': [], 'latest_time': [], 'sub_url': []}
href_list = []
total_list = []
print('从第{}页到第{}页'.format(x, y - 1))
for i in range(x, y):
print('正在第{}页'.format(i))
chrome_options = Options()
chrome_options.add_argument('--headless')
browser = webdriver.Chrome(options=chrome_options)
url = 'http://guba.eastmoney.com/list,{}_{}.html'.format(stock, i)
url2 = 'http://guba.eastmoney.com'
browser.get(url)
html_source = browser.page_source
soup = BeautifulSoup(html_source, "html.parser")
view_num = soup.find_all('span', class_='l1 a1')
comment_num = soup.find_all('span', class_='l2 a2')
title = soup.find_all('span', class_='l3 a3')
poster = soup.find_all('span', class_='l4 a4')
time = soup.find_all('span', class_='l5 a5')
for element in view_num[1:]:
DFCF_dict['view_num'].append(element.string)
for element