我创建了一个spider来从一组用户定义的关键字中抓取Ask搜索结果。但是,每当我运行命令scrapy crawl pageSearch -o test.json
时,它都会为我创建一个空的test.json文件,我不知道为什么。要创建这个api,我的灵感来自于一个开发人员page,他展示了如何抓取谷歌的SERP,以及官方文档中的教程。这是我从命令line中得到的一个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。另外,我请求您的帮助,谢谢!
1条答案
按热度按时间a2mppw5e1#
我发现了两个问题:
名字:
在输出中,您可以看到
这意味着它读取https://www.ask.com/robots.txt并且存在规则
Scrapy尊重它并且跳过url
https://www.ask.com/web?q=love
您必须在您的www.example.com中设置
ROBOTTXT_OBEY = False
settings.py才能关闭它。报废文件:ROBOTTXT_OBEY
第二个:
您使用
di = json.loads(response.text)
,这意味着您需要JSON
数据,但此页面发送HTML
,您必须使用函数response.css(...)
、response.xpath(...)
和.get()
、.attrib.get(...)
等。报废文档:Selectors
工作代码:
您可以将所有代码放在一个
script.py
文件中,并以python script.py
身份运行,而无需创建项目它还将自动将结果保存在test.json
中,而无需使用-o test.json