本文目标从初建scrapy工程到抓取一个论坛页面,涉及问题:
1、F12页面调试
2、xpath
3、输出抓取数据
创建工程
scrapy [object Object]startproject [object Object]tutorial
代码简单仅需修改items.py,spiders/xianzhenyuan_spider.py 2个文件,先列出代码,后再写调试步骤。
items.py
# -*- coding: utf-8 -*- import scrapy from scrapy.item import Item, Field class XianzhenyuanItem(scrapy.Item): catalog = Field() #交易分类 title = Field() #标题 author = Field() #作者 count = Field() #恢复次数
spiders/xianzhenyuan_spider.py
import scrapy from scrapy import Spider class XianzhenyuanSpider(Spider): name = "xianzhenyuan" allowed_domains = ["xianzhenyuan.cn"] start_urls = [ "http://www.xianzhenyuan.cn/forum-24-1.html" ] def parse(self, response): # filename = response.url.split("-")[-2] # with open(filename, ‘wb‘) as f: # f.write(response.body) for sel in response.xpath(‘//tbody/tr‘): title = sel.xpath(‘th/a[1]/text()‘).extract() catalog = sel.xpath(‘th/em/a/text()‘).extract() author = sel.xpath(‘td[2]/cite/a/text()‘).extract() count = sel.xpath(‘td[3]/a/text()‘).extract() print(author, count, catalog, title)
实现结果 :scrapy crawl xianzhenyuan
[‘书记‘] [] [] [] [‘爱家‘] [‘328‘] [] [‘隐藏置顶帖‘] [‘爱家‘] [‘12‘] [‘其它类‘] [‘隐藏置顶帖‘] [‘爱家‘] [‘18‘] [] [‘隐藏置顶帖‘] [‘从水生‘] [‘23‘] [‘其它类‘] [‘隐藏置顶帖‘] [‘花盗‘] [‘4‘] [‘其它类‘] [‘隐藏置顶帖‘] [] [] [] [] [‘zhuminglong‘] [‘2‘] [‘种子类‘] [‘(温州)出售怪龙种夹,怪龙杂种夹,买的多送锦种夹种子包邮包邮快来抢‘] [‘cry1887‘] [‘0‘] [‘12卷‘] [‘【北京】包邮出实生扇苗、实生亚成扇、实生白银、实生克‘] [‘jianzhi1231‘] [‘19‘] [‘种子类‘] [‘【北京】48A、rainbow、荒玉、187、烧麦、绿富贵、毛翠滴、鸽子蛋、小飞、高尔夫‘] [‘duorou12‘] [‘13‘] [‘12卷‘] [‘(浙江杭州)6-4,出几个自养12卷,喜欢就带走吧‘] [‘常州奇奇‘] [‘3‘] [‘12卷‘] [‘(常州)自己繁殖的一批大叶花水晶苗子‘] [‘xly2125101‘] [‘3‘] [‘番杏科‘] [‘【北京】出几个大个189,有个拿铁化的,还有小苗‘] [‘louxuan198611‘] [‘1‘] [‘其它类‘] [‘临沂 满百包邮超级芦荟种子,超级芦荟母本,王妃雷神锦,日月潭亚成,仙女杯及一点...‘] [‘duorou12‘] [‘5‘] [‘12卷‘] [‘(浙江杭州)6-3,出几个自养12卷,喜欢就带走吧‘] [‘st1986725‘] [‘7‘] [‘12卷‘] [‘(上海)出售玉露锦种子,菊水种子,大型霓虹灯,糯玉露等等等‘]
开始说下步骤:
google浏览器 打开页面“http://www.xianzhenyuan.cn/forum-24-1.html”
F12开启调试模式->Elements 用左边箭头 选择想要抓取的数据
我们以title数据为例
下面是xpath的生成方法,选中 邮件copy->copy xpath
下面是找到xpath,貌似不是很通用,有用的地方就是a[1]
//*[@id="normalthread_1443964"]/tr/th/a[1]
这样子 xpath就可以写出来了
我们用一下命令调试 xpath
scrapy shell “http://www.xianzhenyuan.cn/forum-24-1.html”
title的数据能抓出来了,其他几个字段同样方法来抓取
进入xianzhenyuan目录测试一下效果
scrapy crawl xianzhenyuan
时间: 2024-11-05 12:13:27