我創建了一個爬蟲來從一組用戶定義的關鍵字中抓取 Ask 搜索結果。但是,每當我運行命令時,它都會scrapy crawl pageSearch -o test.json為我創建一個空的 test.json 檔案,我不知道為什么。為了創建這個 api,我受到了一個開發者 頁面的啟發,該頁面展示了如何抓取谷歌 SERP 以及來自官方 scrapy 檔案的教程。這是我從命令列得到的git。我從堆疊溢位問題中搜索了解決方案,但沒有成功。我從以下命令提示行中相信:'scrapy.spidermiddlewares.httperror.HttpErrorMiddleware'這是一個 http 錯誤,但在搜索互聯網后它不是,根據我的終端,我的機器人運行成功,并且我在代碼中指定的要進行抓取的 url 地址是有效的。就個人而言,我沒有看到我的錯誤,所以我迷路了。這是我的代碼:
import scrapy
import json
import datetime
class PagesearchSpider(scrapy.Spider):
name = 'pageSearch'
def start_requests(self):
queries = [ 'love']
for query in queries:
url = 'https://www.ask.com/web?q=' query
yield scrapy.Request(url, callback=self.parse, meta={'pos': 0})
def parse(self, response):
print(response.text)
di = json.loads(response.text)
pos = response.meta['pos']
dt = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
for result in di['organic_results']:
title = result['a.PartialSearchResults-item-title-link.result-link']
snippet = result['p.PartialSearchResults-item-abstract']
link = result['div.PartialSearchResults-item-url']
item = {'title': title, 'snippet': snippet, 'link': link, 'position': pos, 'date': dt}
pos = 1
yield item
next_page = di['pagination']['nextPageUrl']
if next_page:
yield scrapy.Request(next_page, callback=self.parse, meta={'pos': pos})
#scrapy crawl pageSearch -o test.json
我使用的是 Windows 10。另外,我請求您的幫助,謝謝!
uj5u.com熱心網友回復:
我發現了兩個問題:
第一的:
在您的輸出中,您可以看到
[scrapy.downloadermiddlewares.robotstxt] DEBUG: Forbidden by robots.txt: <GET https://www.ask.com/web?q=love>
這意味著它讀取https://www.ask.com/robots.txt并且有規則
User-agent: *
Disallow: /web
并且scrapy尊重它并且它跳過了urlhttps://www.ask.com/web?q=love
您必須ROBOTTXT_OBEY = False在 settings.py 中進行設定才能將其關閉。
Scrapy 檔案:ROBOTTXT_OBEY
第二:
您使用di = json.loads(response.text)which 意味著您期望JSON資料,但此頁面發送HTML并且您必須使用函式response.css(...), response.xpath(...)and .get(),.attrib.get(...)等。
Scrapy 檔案:選擇器
作業代碼:
您可以將所有代碼放在一個檔案中script.py并運行,python script.py而無需創建專案。它還會自動保存結果test.json而不使用-o test.json
import scrapy
import datetime
class PagesearchSpider(scrapy.Spider):
name = 'pageSearch'
def start_requests(self):
queries = [ 'love']
for query in queries:
url = 'https://www.ask.com/web?q=' query
yield scrapy.Request(url, callback=self.parse, meta={'pos': 0})
def parse(self, response):
print('url:', response.url)
start_pos = response.meta['pos']
print('start pos:', start_pos)
dt = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
items = response.css('div.PartialSearchResults-item')
for pos, result in enumerate(items, start_pos 1):
yield {
'title': result.css('a.PartialSearchResults-item-title-link.result-link::text').get().strip(),
'snippet': result.css('p.PartialSearchResults-item-abstract::text').get().strip(),
'link': result.css('a.PartialSearchResults-item-title-link.result-link').attrib.get('href'),
'position': pos,
'date': dt,
}
# --- after loop ---
next_page = response.css('.PartialWebPagination-next a')
if next_page:
url = next_page.attrib.get('href')
print('next_page:', url) # relative URL
# use `follow()` to add `https://www.ask.com/` to URL and create absolute URL
yield response.follow(url, callback=self.parse, meta={'pos': pos 1})
# --- run without project, and save in file ---
from scrapy.crawler import CrawlerProcess
c = CrawlerProcess({
#'USER_AGENT': 'Mozilla/5.0',
# save in file CSV, JSON or XML
'FEEDS': {'test.json': {'format': 'json'}},
#'ROBOTSTXT_OBEY': True, # this stop scraping
})
c.crawl(PagesearchSpider)
c.start()
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/486870.html
