刮蹭蜘蛛:不要在lis中抓取网站

2024-04-25 18:56:01 发布

您现在位置:Python中文网/ 问答频道 /正文

目前,我在我的破蜘蛛身上有一条规则:

rules = [Rule(SgmlLinkExtractor(allow=['/item/\d+']), 'parse_item')]

这意味着所有的链接都像www.site.com/item/123654提取并解析。/item/后面的数字是一个唯一的id。spidering的结果将存储在一个json文件中。在

另外,我有一个csv文件,有大约200000个id已经被爬网了,我不想这些网站再次被爬网,以减少服务器负载。假设我创建了一个csv的python列表,如下所示:

^{pr2}$

现在我不希望这些id被忽略,如果这些链接是在爬行过程中发现的,我希望它们存储在json文件中,只需包含信息available=true。 如何做到这一点?我应该在*parse_item*函数中添加第二条规则吗?在

编辑

我的parse_item函数是这样的

def parse_item(self, response):
    sel = Selector(response)
    item = MyItem()
    item['url'] = response.url
    item['name'] = sel.xpath("//h1/text()").extract()
    return item

Tags: 文件csv函数idjsonurlparse链接
1条回答
网友
1楼 · 发布于 2024-04-25 18:56:01

SgmlLinkExtractor接受process_value可调用:

a function which receives each value extracted from the tag and attributes scanned and can modify the value and return a new one, or return None to ignore the link altogether. If not given, process_value defaults to lambda x: x.

所以这样做应该有帮助:

def process_value(value):
    unique_id = re.search(r"/item/(\d+)", value).group(1)
    if unique_id in already_crawled_site_ids:
        return None
    return value

rules = [Rule(SgmlLinkExtractor(allow=['/item/\d+']), 'parse_item', process_value=process_value)]

相关问题 更多 >