python - 解析方法的 Scrapy 参数
问题描述
我正在用 Python Scrapy 编写一个网络爬虫,它爬过标签目录的多个页面并获取所有标签及其文章。
所以我得到了这个解析方法,蜘蛛在每个页面中运行。
def parse_word(self, response):
# look for all tags on this site
tagscount = response.xpath('someXpath').extract()
# check if there is a nextPage
nextPage = response.css('somecssSelector').extract()
lastPage = response.css('somecssSelector').extract()
# Open every tagsite and crawl it if all tags are gained
if not nextPage or lastPage:
for tag in tagscount:
# call parse method for article crawling
data = scrapy.Request(url=tag, callback=self.parse_subpage)
yield data
# If there is a nextPage with tags request with this method recursively
else:
# a little bit of formatting for linktype
nextPageStr = str(nextPage)
cutNextPageStr = nextPageStr.replace("[","")
cutNextPageStr = cutNextPageStr.replace("]", "")
cutNextPageStr = cutNextPageStr.replace("'", "")
link = urljoin(response.url, cutNextPageStr)
# Call this method again --> here i want to set a parameter tagscount or something like this
data = scrapy.Request(url=link, callback=self.parse_word)
yield data
在其他部分,我想为 parse_word 方法提供获得的标签,但整个方法只采用最后一个站点的标签。
谁能帮我?
解决方案
要提出替代解决方案,您可以使用蜘蛛中间件来执行计数,该中间件将存储在请求/响应元字典中。
从某种意义上说,计数的责任与从页面中选择元素的责任是分开的,这更简洁一些。
推荐阅读
- kubernetes-helm - 我们可以在分蘖而不是掌舵客户端中进行图表安装吗?
- amazon-web-services - 如何知道我的实例是否会在 ec2 中终止?
- android - 如何修复 android studio 3 中的“找不到符号类 Nullable”错误
- stripe-payments - Stripe:有没有一种元素可以免费创造客户?
- javascript - 在 Spark AR studio 中获取像素屏幕尺寸(适用于 Facebook)
- xml - 如何从 xml 文件构建 xsd?
- azure-application-insights - 启动 Application Insights Agent for Java 时出错
- python - 适用于 Apache Flink 的 Python API 上的 Kafka 连接器
- typescript - 在 JS 中测试异步函数 - 错误:“您是否忘记使用 await”
- sql - 如何在 SQL Server 中计算给定每日帐户余额的 MTD?