我已经构建了一个可以工作的scrapy解析器,我正在从一个json文件加载设置以设置xPaths以进行抓取和其他设置。
{
"urlEntry": "https://www.realcommercial.com.au/for-sale/",
"urlDomain": ".*realcommercial.com.au/for-sale/.*",
"urlScrape": ".*?\\d{9}",
"bindings": [
{
"name": "ID",
"xPath": "//span[contains(@class, \"propertyId\")]/text()",
"filter": "\\d{9}"
},
...
有一堆绑定。我正在像这样成功地将设置文件加载到蜘蛛中
self.settings = json.load(open("./Scrapy_Agent/config/" + self.name + ".json"))
稍后我会担心路径的硬编码部分,但配置文件是基于蜘蛛名称的。
但是我遇到麻烦的地方是我有一个管道想要使用配置文件中的过滤器字段。
我有一个看起来像这样的 ItemLoader
class ListingLoader(ItemLoader):
PostcodeName_out = OutputRegexProcessor("PostcodeName")
ID_out = OutputRegexProcessor("ID")
AddressName_out = OutputRegexProcessor("AddressName")
和输出 RegexProcessor 的 init 看起来像这样
class OutputRegexProcessor(object):
def __init__(self, name):
settings = json.load(open("./Scrapy_Agent/config/realcommercialsale.json"))
self.regex = ""
for binding in settings["bindings"]:
if (binding["name"] == name):
if (binding.get("filter")):
self.regex = binding["filter"]
蜘蛛的名字是 realcommercialsale,目前这里是硬编码的。我是一个 python 初学者,我一直在努力寻找一种方法来获取当前蜘蛛的名称。
我不致力于任何特定的解决方案。我需要在 OutputRegexProcessor 中获取 item 字段的正则表达式字符串。我是否访问蜘蛛的名称并像我目前正在做的那样重新解析 json 文件,或者以其他方式传递 json 文件,或者我不知道的其他解决方案。