第一次使用scrapy,記下爬過的坑
第一次使用scrapy,記下爬過的坑
1,xpath語法,xpath語法用於選取需要的數據,用過bs4會比較好的理解它,類似於從一目錄樹查找,
xpath(‘/html/body/div/div‘),這是絕對路徑找數據
xpath(‘//*[@id = “niubi”]‘),這是相對路徑找數據
還可以選擇從絕對路徑到某一路徑下,找一個“特殊”的數據
xpath(‘//*a/html/body/div1/div2),找div2下的所有a標簽
2,找到後,需要實例化,這是第二個坑,實例化有extract()函數,然後才能轉換成字符串,之後就能操作數據了
3,在爬蟲腳本中,spider中,如果需要定義全局變量,千萬不能定義name,估計一些scrapy的關鍵字也不能定義,不然爬蟲莫名死掉
4,回調函數,parse中的值,不能傳入回調函數中,不知道是不是我技術不行呢,就是傳不進去- -
5,item,在起始位置,from導入之後,需要在使用的函數內,或者說class中定義靜態方法,item = xxxitem(),不然它不認識你的數組,但是在pipeline中卻不需要
1 # -*- coding: utf-8 -*-
import scrapy
from text.items import TextItem
import sys
class ExampleSpider(scrapy.Spider):
name = "qunimade"
allowed_domains = ["biquge.com.tw"]
start_urls = ( 10 ‘http://www.biquge.com.tw/11_11850‘,)
global d,n
d = {} 13 n = ‘‘
def parse(self,response):
shou = response.xpath(‘/html/body/div/div/div/dl/dd/a/@href‘)
wen = response.xpath(‘/html/body/div/div/div/dl/dd/a/text()‘)
n = response.xpath(‘/html/body/div/div/div/div/h1/text()‘).extract()[0]
x = 1
for t in wen.extract():
t.strip() 21 d[t] = x
x = x + 1 23 po = ‘http://www.riven.cc‘
for i in shou.extract(): 26 p = po + i 27 yield scrapy.Request(p,callback = self.parse_1) 28 29 30 31 32 def parse_1(self, response): 33 item = TextItem() 34 h1 = response.xpath(‘/html/body/div/div/div/div/h1/text()‘) 35 r = h1[0].extract() 36 r = r.strip() 37 item[‘zhangjie‘] = r 38 tt = d[r]
第一次使用scrapy,記下爬過的坑