gpt4 book ai didi

python - Scrapy 部署与调试结果不匹配

转载 作者:行者123 更新时间:2023-12-01 05:03:28 25 4
gpt4 key购买 nike

我正在使用 Scrapy 从网站(例如“myproject.com”)中提取一些数据。逻辑如下:

  1. 转到主页,有一些用于构建第二波链接的categorylist
  2. 对于第二轮链接,它们通常是每个类别的首页。此外,对于该类别内的不同页面,它们遵循相同的正则表达式模式wholesale/something/something/request 或wholesale/pagenumber。我想遵循这些模式继续爬行,同时将原始 HTML 存储在我的项目对象中。

我使用 parse 分别测试了这两个步骤他们都工作了。

首先,我尝试了:

scrapy parse http://www.myproject.com/categorylist/cat_a --spider myproject --rules 

我可以看到它成功构建了外链。然后我再次测试了构建的外链。

scrapy parse http://www.myproject.com/wholesale/cat_a/request/1 --spider myproject --rules

看起来规则是正确的,它会生成一个项目,其中存储有 HTML。

但是,当我尝试使用 深度 参数将这两个步骤链接在一起时。我看到它抓取了外链,但没有生成任何项目。

scrapy parse http://www.myproject.com/categorylist/cat_a --spider myproject --rules --depth 2

这是伪代码:

class MyprojectSpider(CrawlSpider):
name = "Myproject"
allowed_domains = ["Myproject.com"]
start_urls = ["http://www.Myproject.com/"]

rules = (
Rule(LinkExtractor(allow=('/categorylist/\w+',)), callback='parse_category', follow=True),
Rule(LinkExtractor(allow=('/wholesale/\w+/(?:wholesale|request)/\d+',)), callback='parse_pricing', follow=True),
)

def parse_category(self, response):
try:
soup = BeautifulSoup(response.body)
...
my_request1 = Request(url=myurl1)
yield my_request1
my_request2 = Request(url=myurl2)
yield my_request2
except:
pass

def parse_pricing(self, response):
item = MyprojectItem()
try:
item['myurl'] = response.url
item['myhtml'] = response.body
item['mystatus'] = 'fetched'
except:
item['mystatus'] = 'failed'
return item

非常感谢您的建议!

最佳答案

我假设我构建的新 Request 对象将根据 rules 运行,然后由规则中定义的相应回调函数进行解析,但是,在阅读之后documentation对于 Request,callback 方法以不同的方式处理。

class scrapy.http.Request(url[, callback, method='GET', headers, body, cookies, meta, encoding='utf-8', priority=0, dont_filter=False, errback])

callback (callable) – the function that will be called with the response of this request (once its downloaded) as its first parameter. For more information see Passing additional data to callback functions below. If a Request doesn’t specify a callback, the spider’s parse() method will be used. Note that if exceptions are raised during processing, errback is called instead.

...
my_request1 = Request(url=myurl1, callback=self.parse_pricing)
yield my_request1
my_request2 = Request(url=myurl2, callback=self.parse_pricing)
yield my_request2
...

换句话说,即使我构建的 URL 符合第二条规则,它也不会传递到 parse_pricing。希望这对其他人有帮助。

关于python - Scrapy 部署与调试结果不匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25530998/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com