我正在使用抓取广泛爬行,并有以下要求:
file1.json
,当且仅当file1.json
的大小小于2GB
时。否则,Scrapy将创建一个新文件,比如file2.json
,并编写对这个新文件的响应;下面是我的代码,我能够执行步骤1&步骤3,但不知道应该把creating the new file
、checking the size
和writing the response
的逻辑放在哪里。
def parse(self, response):
url = response.request.url
soup = BeautifulSoup(response.text, 'lxml')
d = {}
for element in soup.find_all():
if element.name in ["html", "body", "script", "footer"]:
pass
else:
x = element.find_all(text=True, recursive=False)
if x:
d[element.name] = x
yield d ---------> I want to write this dictionary in a file as per logic of step 2
for link in soup.find_all('a', href=True):
absoluteUrl = urllib.parse.urljoin(url, link['href'])
parsedUrl = urlparse(absoluteUrl)
if parsedUrl.scheme.strip().lower() != 'https' and parsedUrl.scheme.strip().lower() != 'http':
pass
else:
url = url.replace("'", r"\'")
absoluteUrl = absoluteUrl.replace("'", r"\'")
self.graph.run(
"MERGE (child:page{page_url:'" + url + "'}) " +
"On CREATE " +
"SET child.page_url='" + url + "', child.page_rank = 1.0 " +
"MERGE (parent:page{page_url:'" + absoluteUrl + "'}) " +
"On CREATE " +
"SET parent.page_url = '" + absoluteUrl + "' , parent.page_rank = 1.0 " +
"MERGE (child)-[:FOLLOWS]->(parent)"
)
yield response.follow(absoluteUrl, callback=self.parse). ---> Step 3 ( all good )
我的问题是,应该将创建文件、检查文件大小和将蜘蛛响应写入该文件的逻辑(应该在管道、中间件或init函数中)的逻辑写在哪里?
任何帮助都将不胜感激。我试着学习中间件、管道等等,但无法理解如何实现这个功能。
发布于 2022-04-06 19:50:00
如果您知道每个文件应该持有的项的大致数量不超过2GB的限制大小,那么就可以使用FEED_EXPORT_BATCH_ITEM_COUNT
设置,当文件中的项数达到上述限制时,scrapy将自动创建新文件。在饲料页面上阅读有关此设置的更多信息。
https://stackoverflow.com/questions/71772022
复制