爬取虎牙之一:(王者荣耀主播信息普通爬取)
使用工具 jsoup
对于新手而言,jsoup无疑是最简单的抓取工具之一,强大的解析能力让人方便使用,对于我们新手而言,获取只是看过爬虫书或者资料用简单的例子爬取所有链接,想要爬取想要的内容,首先要熟悉html网页的架构,然后还要熟悉jsoup的简单用法,只会遍历所有链接是不行的。
首先打开王者荣耀分栏,看到这样的界面:
;
如果我们想爬取所有主播的信息,我们首先要确定的是要爬取的是主播的信息而不是查看网页源码:
我们发现这里虽然有些乱,每个主播的类,类中含有的内容确是可以找到的,我们发现game-live-item这个类是主播的最大类,主播的基本信息都藏在他的内容里或者他的子class中,这样我们就可以第一次遍历这个最大的类,然后从这个类中我们需要什么,再筛选什么详细看代码:
import java.io.IOException;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
public class jsoup爬取虎牙 {
public static void main(String[] args) throws ClassNotFoundException, IOException
{
String ul="https://www.huya.com/g/wzry";//分类的首页
Connection conn = Jsoup.connect(ul); Document doc= conn.userAgent("Mozilla").timeout(3000).get(); // System.out.println(links);
//Elements links = doc.getElementsByClass("avatar fl");//主播昵称
//Elements links = doc.getElementsByClass("txt");//可以遍历到人数和主播昵称
//Elements links = doc.getElementsByClass("title new-clickstat");//链接和标题
Elements links = doc.getElementsByClass("game-live-item");//可以遍历到人数标题 是最大的类
for(Element link: links)//遍历链接
{ /* * 链接再这个html文档中的子类title new-clickstat中在分析这个元素 */ Document doe=Jsoup.parse(link.html()); Elements e2 =doe.getElementsByClass("title new-clickstat"); System.out.print(e2.attr("href")); String a=link.attr("href");//href链接 String b=link.text(); //内容文字 int c=Integer.parseInt(link.attr("gid")); System.out.print(b " : \t"); System.out.println(c); } }
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
输出的内容为:
https://www.huya.com/housangun大神推荐 射手新出装-新赛季鲁3枪上王者 China丶猴三棍 40.5万 : 2336
https://www.huya.com/131499年度推荐 蓝光4M 寒冰:单排上第三个王者~ 东辰-寒冰 18.0万 : 2336
https://www.huya.com/942020大神推荐 蓝光4M 上好佳:赛季初 5排怒撞职业小代 求虐! 上好佳 10.9万 : 2336
https://www.huya.com/chaojie大神推荐 无敌小射手已上线!! 东辰-小潮 10.7万 : 2336
https://www.huya.com/tingxiaojie白金推荐 88胜率貂蝉重新冲国服 Dae-婷小姐 3.6万 : 2336
https://www.huya.com/11428718大神推荐 国服第一露娜上第四个王者! 电竞浪子傲寒 5.4万 : 2336
***************************
***************************
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
这仅仅是爬取第一页的内容。我们如果想要爬取所有王者荣耀主播的信息或者甚至虎牙直播的信息,理论上应该是爬取完当页的信息之后再爬取下一页的链接,但是你会发现无济于事,因为这个页面和第二个页面是一个链接。这个页面是ajax的动态生成页面,传统爬取静态方法的方式只能告一段落。采用其他方法。下一篇在做介绍。
如果对后端、爬虫等感性趣欢迎关注我的个人公众号交流:bigsai
文章来源: bigsai.blog.csdn.net,作者:Big sai,版权归原作者所有,如需转载,请联系作者。
原文链接:bigsai.blog.csdn.net/article/details/80066484
- 点赞
- 收藏
- 关注作者
评论(0)