[英]ScraPy spider crawling but not exporting
我有一個在外殼程序中運行的ScraPy代碼,但是當我嘗試將其導出到csv時,它將返回一個空文件。 當我不進入鏈接並嘗試解析描述時,它將導出數據,但是一旦我添加了解析內容的額外方法,它便無法工作。 這是代碼:
class MonsterSpider(CrawlSpider):
name = "monster"
allowed_domains = ["jobs.monster.com"]
base_url = "http://jobs.monster.com/v-technology.aspx?"
start_urls = [
"http://jobs.monster.com/v-technology.aspx"
]
for i in range(1,5):
start_urls.append(base_url + "page=" + str(i))
rules = (Rule(SgmlLinkExtractor(allow=("jobs.monster.com",))
, callback = 'parse_items'),)
def parse_items(self, response):
sel = Selector(response)
sites = sel.xpath('//div[@class="col-xs-12"]')
#items = []
for site in sites.xpath('.//article[@class="js_result_row"]'):
item = MonsterItem()
item['title'] = site.xpath('.//span[@itemprop = "title"]/text()').extract()
item['company'] = site.xpath('.//span[@itemprop = "name"]/text()').extract()
item['city'] = site.xpath('.//span[@itemprop = "addressLocality"]/text()').extract()
item['state'] = site.xpath('.//span[@itemprop = "addressRegion"]/text()').extract()
item['link'] = site.xpath('.//a[@data-m_impr_a_placement_id= "jsr"]/@href').extract()
follow = ''.join(item["link"])
request = Request(follow, callback = self.parse_dir_contents)
request.meta["item"] = item
yield request
#items.append(item)
#return items
def parse_dir_contents(self, response):
item = response.meta["item"]
item['desc'] = site.xpath('.//div[@itemprop = "description"]/text()').extract()
return item
刪除parse_dir_contents並取消注釋空的“列表”列表和“追加”代碼是原始代碼。
好吧,正如@tayfun建議的那樣,您應該使用response.xpath
或定義site
變量。
順便說一句,您不需要使用sel = Selector(response)
。 響應是xpath
函數附帶的,無需將其覆蓋到另一個選擇器中。
但是,主要問題是您限制了蜘蛛網的域。 您可以定義allowed_domains = ["jobs.monster.com"]
但是如果你看一下網址follow
您的自定義的Request
,你可以看到,他們是像http://jobview.monster.com/
或http://job-openings.monster.com
。 在這種情況下,不會執行parse_dir_contents
(不允許使用域),並且不會返回您的item
,因此您不會得到任何結果。
將allowed_domains = ["jobs.monster.com"]
更改為
allowed_domains = ["monster.com"]
一切都會好起來的,您的應用將可以正常工作並退貨。
您的parse_dir_contents
方法中有一個錯誤:
def parse_dir_contents(self, response):
item = response.meta["item"]
item['desc'] = response.xpath('.//div[@itemprop=description"]/text()').extract()
return item
注意使用response
。 我不知道您當前從何處獲得site
。
另外,在發布問題時,請嘗試提供錯誤詳細信息。 寫“行不通”並沒有多說。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.