本次编程主要是为了练习爬虫编程和数据分析,对斗鱼直播进行爬虫,按区域划分获取主播信息并用pandas进行数据处理,用matplotlib进行绘图。
用到的功能有:requests主要爬虫模块、threading多线程模块、pandas数据处理模块、queue队列模块、lxml HTML解析器、matplotlib 绘图模块、time模块。
另外一篇记录主播热度的文章可以浏览一下:
https://blog.youkuaiyun.com/New_boy25/article/details/101067531
思路如下:
- 先从斗鱼主页(https://www.douyu.com/directory/all)中爬取分区的名称以及网址
- 分别向每个分区发送请求并获取响应
- 用xpath从每个响应中获取每个分区首页的主播名称及其热度
- 用pandas对获取到的主播信息按热度进行排序
- 将排序好的数据用matplotlib呈现出来(条形图)
(另外使用到了队列和多线程进行工作)
代码如下,欢迎学习交流:
# coding=utf-8
import requests
import threading
import pandas as pd
import time
from queue import Queue
from lxml import etree
from matplotlib import font_manager, use
use('Agg')
from matplotlib import pyplot as plt
class DouyuSpider:
def __init__(self):
self.headers = {
"user-agent":"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.3", }
self.Index = "https://www.douyu.com/directory/all"
# 创建队列
self.module_queue = Queue()
self.module_content_queue = Queue()
self.module_th_queue = Queue()
self.main_info_queue = Queue()
self.plot_info_queue = Queue()
# 请求链接返回响应
def parse_url(self, url):
response = requests.get(url, headers=self.headers)
return response.content.decode()
# 使用xpath获取每个分区
def get_module(self, index_html):
html = etree.HTML(index_html)
module_list = html.xpath('''//a[@class="Aside-menu-item"]''')
for temp in module_list:
self.module_queue.put(temp)
print(len(module_list))
# 获取每个分区的名称和链接
def get_module_content(self):
while True:
temp = []
module = self.module_queue.get()
title = module.xpath('''./@title''')[0] if len(module.xpath('''./@title'''))