Scrapy爬取网页数据

Scrapy爬取并保存网页数据

网页爬取在上一篇博客中已写过,在这里不在写相关步骤,需要的可以查看上一篇博客。

地址为:https://blog.csdn.net/csdnmgq/article/details/88703019



itcast.py文件下的代码替换为:

import scrapy
from test002.items import ItcastItem
class ItcastSpider(scrapy.Spider):
    name = "itcast"
    allowed_domains = ["itcast.cn"]
    start_urls = ("http://www.itcast.cn/channel/teacher.shtml",)

    def parse(self, response):
        filename = "test.html"
        open(filename, 'wb').write(response.body)
        items = []

        for each in response.xpath("//div[@class='li_txt']"):
            # 将我们得到的数据封装到一个 `ItcastItem` 对象
            item = ItcastItem()
            # extract()方法返回的都是unicode字符串
            name = each.xpath("h3/text()").extract()
            title = each.xpath("h4/text()").extract()
            info = each.xpath("p/text()").extract()

            # xpath返回的是包含一个元素的列表
            item['name'] = name[0]
            item['title'] = title[0]
            item['info'] = info[0]

            items.append(item)

        # 直接返回最后数据
        return items

如下所示:

到这里如果引用出错,添加etree包即可。添加方法为:

添加etree包即可解决问题。

接下来在终端执行命令:

scrapy crawl itcast -o test.xml

test.xml为保存爬取数据文件及格式;

执行命令之后在文件夹下会出现test.xml文件。

打开此文件,里面就是我们爬取的内容:

 

此外也可以保存为其他格式:csv、json、jsonl.

 

爬取内容完毕!!

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值