今天我们对虎牙平台的lol板块的主播信息进行爬取,主要爬取主播名称,以及观看人数。
下面我们先来分析一下网页源吧:
这张图片下面的翻页列表是动态的,随着上线的主播越来越多,翻页的列表也会越来越大。
通过XpathHelper工具我们可以找到主播网名对应的xpath路径,同理我们可以找到对应观看人数的xpath
下面我们开始编写代码吧。
本次爬虫练习,我们使用selenium模块进行爬取,使用selenium不用关注网页是静态的,还是动态的,直接进行加载就可以了
# 使用selenium不用关注网页是静态的,还是动态的,直接进行加载就可以了from selenium import webdriver# 通过webdriver创建一个浏览器driver = webdriver.Chrome()url = "/g/lol"# 通过创建的浏览器发送请求driver.get(url)# 获取网页源代码html = driver.page_source# 进行网页解析# 使用find_elements_by容易报错,最好还是用我们以前的xpath技术names = driver.find_elements_by_xpath("//i[@class='nick']")counts = driver.find_elements_by_xpath("//span[@class='num']")for name, count in zip(names, counts):print(name.text, ":", count.text)
这样我们的爬虫代码1.0就写好了,不过缺陷是只能爬取一页内容。
下面我们来讲解如何在原有代码基础上爬取更多的页面。
我们先通过源码查看一下如何控制翻页的。
从图中可以看出翻页控制使用了
下面我们使用if判断条件进行翻页操作,当然这个操作要写在while循环中。
# 使用selenium不用关注网页是静态的,还是动态的,直接进行加载就可以了from selenium import webdriver# 通过webdriver创建一个浏览器driver = webdriver.Chrome()url = "/g/lol"# 通过创建的浏览器发送请求driver.get(url)while True:# 获取网页源代码html = driver.page_source# 进行网页解析# 使用find_elements_by容易报错,最好还是用我们以前的xpath技术names = driver.find_elements_by_xpath("//i[@class='nick']")counts = driver.find_elements_by_xpath("//span[@class='num']")# 循环打印网名与人数for name, count in zip(names, counts):print(name.text, ":", count.text)# -1表示,找不到laypage_next元素字样if driver.page_source.find("laypage_next") != -1:# 针对“下一页”进行解析,这到这个元素进行点击操作即可driver.find_element_by_xpath("//a[@class='laypage_next']").click()else:break
写好代码后,运行发现出错了。
报错代码如下:
raise exception_class(message, screen, stacktrace)mon.exceptions.StaleElementReferenceException: Message: stale element reference: element is not attached to the page document(Session info: chrome=88.0.4324.104)
造成这种错误的原因是我们的网速太慢,导致网页加载速度跟不上网页解析速度,致使出现错误,我们只需在网页加载前面使用sleep(5)让其休眠等待即可。
最终修改的代码为:
# 使用selenium不用关注网页是静态的,还是动态的,直接进行加载就可以了from selenium import webdriverfrom time import sleep# 通过webdriver创建一个浏览器driver = webdriver.Chrome()url = "/g/lol"# 通过创建的浏览器发送请求driver.get(url)num = 1while True:print("第" + str(num) + "页-------------------------------------")num += 1# 获取网页源代码sleep(5)html = driver.page_source# 进行网页解析# 使用find_elements_by容易报错,最好还是用我们以前的xpath技术names = driver.find_elements_by_xpath("//i[@class='nick']")counts = driver.find_elements_by_xpath("//span[@class='num']")for name, count in zip(names, counts):print(name.text, ":", count.text)# -1表示,找不到laypage_next元素字样if driver.page_source.find("laypage_next") != -1:# 针对“下一页”进行解析,这到这个元素进行点击操作即可driver.find_element_by_xpath("//a[@class='laypage_next']").click()else:break
终于一波三折编写好了这段代码。
下面看一下运行过程吧: