python爬虫-使用request,lxml库爬取游戏排名

爬取目标URL:http://wy.hao123.com/top
开发环境:

  • PyCharm 2019.2.3
  • Python3.6
  • 火狐浏览器

使用的三方库:

  • requests
  • lxml

执行结果

执行结果

开始

抓取网页

打开火狐浏览器,输入地址 http://wy.hao123.com/top ;
按F12功能键,启动调试功能;
调试界面通过分析使用下面的xpath代码可以获取到想要的数据

"//div[@class='list1 margin-right']|//div[@class='list1 ']"

匹配结果

编写爬虫代码

spider_hao123_01.py

"""
    爬取hao123网站的网络游戏排行榜
    http://wy.hao123.com/top
"""
import requests
from lxml import etree


def load_context():
    """ 获取http://wy.hao123.com/top网页内容 """

    # 定义HTTP请求头
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:75.0) Gecko/20100101 Firefox/75.0'
    }
    # url地址
    url = "http://wy.hao123.com/top"

    # 使用requests的get方法获取网页内容
    rsp_ctx = requests.get(url, headers=headers)
    # 返回网页内容
    return rsp_ctx.text


def parse_context(c):
    html = etree.HTML(c)
    # 获取全部排名div标签
    divs = html.xpath("//div[@class='list1 margin-right']|//div[@class='list1 ']")
    with open('./hao123_wy_top.txt', 'w') as f:
        for div in divs:
        	# 获取排名的名称
            title = div.xpath("./div[@class='tlt']")[0].text
            # print(title)
            f.write(title + '\n')
            # 获取排名数据项
            games = div.xpath(".//li")
            for idx, game in enumerate(games):
            	# 获取游戏名称
                game_name = game.xpath("./p/a")[0].text
                # 获取游戏类型
                game_type = game.xpath("./em")[0].text
                f.write("\t" + str(idx+1) + "\t" + game_name + "\t" + game_type + '\n')
    print("hao123网游排名获取完毕。")


if __name__ == "__main__":
    ctx = load_context()
    parse_context(ctx)

结语

这是一个简单的爬虫例子,爬取的是一个静态页面。在html页面解析时使用到了xpath语法。
希望对你有所帮助。

XPath教程.

  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值