首页
学习
活动
专区
圈层
工具
发布
社区首页 >专栏 >爬虫入门经典(九) | 简单一文教你如何爬取扇贝单词

爬虫入门经典(九) | 简单一文教你如何爬取扇贝单词

作者头像
不温卜火
发布2020-10-29 13:00:47
发布2020-10-29 13:00:47
1K0
举报
文章被收录于专栏:不温卜火不温卜火

扇贝Python必背词汇网址:https://www.shanbay.com/wordlist/110521/232414/

一、网页分析

我们打开此网站之后,通过以往爬取网页的经验,会发现此网页特别容易爬取。

大概查看了网页,我们只需爬取单词和含义即可。首先我们先来查看网页源码

下面分别把他们解析出来:

?,分析完毕后,我们就可以通过代码进行实现了。

代码语言:javascript
复制
    etree_obj = etree.HTML(html)
    word_list = etree_obj.xpath('//strong/text()')
    explain_list = etree_obj.xpath('//td[@class="span10"]/text()')
    item_zip = zip(word_list,explain_list)
    for item in item_zip:
        items.append(item)

分析完内容,下面就开始分析分页。鉴于此URL只有三页URL,因此,博主就使用最简单的方式,把Url拼接出来

代码语言:javascript
复制
base_url = "https://www.shanbay.com/wordlist/110521/232414/?page={}"

for i in range(1, 4):
    url = base_url.format(i)
    print(url)

二、代码实现

代码语言:javascript
复制
# encoding: utf-8
'''
  @author 李华鑫
  @create 2020-10-08 8:10
  Mycsdn:https://buwenbuhuo.blog.csdn.net/
  @contact: 459804692@qq.com
  @software: Pycharm
  @file: 作业:爬扇贝Python必背词汇.py
  @Version:1.0
  
'''
import csv
import requests
from lxml import etree

"""
https://www.shanbay.com/wordlist/110521/232414/?page=1
https://www.shanbay.com/wordlist/110521/232414/?page=2
https://www.shanbay.com/wordlist/110521/232414/?page=3

//strong                         # en
//td[@class="span10"]            # cn
"""
base_url = "https://www.shanbay.com/wordlist/110521/232414/?page={}"

headers={
    'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36',
}

items =[]

def parse_url(url):
    """解析url,得到响应内容"""
    response = requests.get(url=url,headers=headers)
    return response.content.decode("utf-8")

def parse_html(html):
    """使用xpath解析html"""
    etree_obj = etree.HTML(html)
    word_list = etree_obj.xpath('//strong/text()')
    explain_list = etree_obj.xpath('//td[@class="span10"]/text()')
    item_zip = zip(word_list,explain_list)
    for item in item_zip:
        items.append(item)

def svae():
    """将数据保存到csv中"""
    with open("./shanbei.csv", "a", encoding="utf-8") as file:
       writer = csv.writer(file)
       for item in items:
            writer.writerow(item)

def start():
    """开始爬虫"""
    for i in range(1, 4):
        url = base_url.format(i)
        html = parse_url(url)
        parse_html(html)
    svae()

if __name__ == '__main__':
    start()

三、运行结果

美好的日子总是短暂的,虽然还想继续与大家畅谈,但是本篇博文到此已经结束了,如果还嫌不够过瘾,不用担心,我们下篇见!

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2020/10/25 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 一、网页分析
  • 二、代码实现
  • 三、运行结果
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档