Scrapy限制中间目录(Python)

2024-10-04 03:29:36 发布

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

在SgmlLinkExtractor规则中有没有一种方法只允许在/static/和/otherstuff/之间有有限数量的目录(比如3个)?因此,在下面的示例中,不会对EX1进行爬网(因为/static/和/otherstuff/之间有四个目录),但会对EX2进行爬网。你知道吗

例1:http://www.domain.com/static/d1/d2/d3/d4/otherstuff/otherstuff2/bunchacrap
EX2:http:///www.domain.com/static/d1/d2/otherstuff/otherstuff2/bunchacrap

假设/static/和/otherstuff/总是在我想要的目录的两侧。你知道吗

非常感谢你的帮助!你知道吗


Tags: 方法目录comhttp规则domainwwwstatic
1条回答
网友
1楼 · 发布于 2024-10-04 03:29:36

可以在allow参数中使用regex,也可以在process_value参数中使用测试函数。(参见docs。)

两者都有各自的优点和缺点,这取决于它在页面中的链接看起来如何。如果您使用regex,那么您将针对完全限定的url(即http://domain.com/foo/bar)进行测试。如果您使用process_value参数,您将得到在网页中找到的原始值(即/foo/bar或更糟的,相对链接)。你知道吗

例如,正则表达式domain.com/(?:\w+/){1,3}\w+$匹配

domain.com/foo/bar
domain.com/foo/bar/foo
domain.com/foo/bar/foo/bar

但不是

domain.com/foo/
domain.com/foo/bar/foo/bar/foo

如果使用process_value,这样的函数就可以工作了

def filter_path(value):
    # at least 2, at most 3 /'s
    if 1 < value.count('/') < 4:
        return value

上面的函数假设您的html链接具有href值,如/foo/foo/bar/foo

在您的特定情况下,regex类似于domain.com/static/(?:\w+/){3}otherstufffilter_path函数可能会检查value.startswith('/static/')和后缀。你知道吗

如果您在CrawlSpider中使用Rule类,那么还有第三个选项。process_links参数允许您传递一个函数来处理链接列表。例如

def url_allowed(url):
    # check for the pattern /static/dir/dir/dir/ etc
    return True

def process_links(links):
    return [l for l in links if url_allowed(l.url)]

相关问题 更多 >