我有一个简单的蜘蛛,它从页面上的脚本中刮取一些东西
我把剧本删去了
jsData = json.loads(response.xpath('//script[@type="application/ld+json"]//text()').extract_first())
当我在spider中从一个项目中运行它时,我得到了所有的数据,但是如果我从一个常规脚本中运行它,而不是在一个项目中,它不会从脚本中得到所有的数据。为什么呢
这是我的脚本蜘蛛
import scrapy
import json
from scrapy.crawler import CrawlerProcess
class MySpider(scrapy.Spider):
name = "target"
start_urls = ['https://www.target.com/p/madden-nfl-22-xbox-one-series-x/-/A-83744898#lnk=sametab']
def parse(self, response):
jsData = json.loads(response.xpath('//script[@type="application/ld+json"]//text()').extract_first())
NAME_SELECTOR = jsData['@graph'][0]
yield {
'name': NAME_SELECTOR,
}
process = CrawlerProcess()
process.crawl(MySpider)
process.start()
它给了我
...'offers': {'@type': 'Offer', 'priceCurrency': 'USD', 'availability': 'InStock', 'availableDeliveryMethod': 'ParcelService', 'potentialAction': {'@type': 'BuyAction'}, 'url': 'https://www.target.com/p/madden-nfl-22-xbox-one-series-x/-/A-83744898'}}}
我的项目代码是
import scrapy
import json
class targetSpider(scrapy.Spider):
name = "target"
start_urls = ['https://www.target.com/p/madden-nfl-22-xbox-one-series-x/-/A-83744898#lnk=sametab']
def parse(self, response):
jsData = json.loads(response.xpath('//script[@type="application/ld+json"]//text()').extract_first())
test = jsData['@graph'][0]
yield {
'test': test
}
它给了我
...'offers': {'@type': 'Offer', 'price': '59.99', 'priceCurrency': 'USD', 'availability': 'PreOrder', 'availableDeliveryMethod': 'ParcelService', 'potentialAction': {'@type': 'BuyAction'}, 'url': 'https://www.target.com/p/madden-nfl-22-xbox-one-series-x/-/A-8
3744898'}}}
这是关于javascript的。像
'price': '59.99'
这样的内容由javascript加载。默认情况下,Scrapy中的Downloader
不支持运行javascript你问题的可能原因
CrawlerProcess()
开头的脚本未在项目根目录下运行,这导致settings.py
无法加载李>更新:抱歉,我忘了在使用
CrawlerProcess()
时需要手动加载设置Run scrapy from a script相关问题 更多 >
编程相关推荐