python - Scrapy 自定义链接提取器以限制跟随的链接数量
问题描述
我正在尝试编写一个基于 Scrapy 的自定义链接提取器LxmlLinkExtractor
。这个想法是包含一个maxpages
参数,以在达到限制后停止跟踪该域的链接(并继续下一个)。但是,我无法让我的自定义链接提取器工作:
from scrapy.linkextractors.lxmlhtml import *
class LimitedLinkExtractor(FilteringLinkExtractor):
def __init__(self, allow=(), deny=(), allow_domains=(), deny_domains=(), restrict_xpaths=(),
tags=('a', 'area'), attrs=('href',), canonicalize=False,
unique=True, process_value=None, deny_extensions=None, restrict_css=(),
strip=True, maxpages=10): #added maxpages
tags, attrs = set(arg_to_iter(tags)), set(arg_to_iter(attrs))
tag_func = lambda x: x in tags
attr_func = lambda x: x in attrs
lx = LxmlParserLinkExtractor(
tag=tag_func,
attr=attr_func,
unique=unique,
process=process_value,
strip=strip,
canonicalized=canonicalize,
)
super(FilteringLinkExtractor, self).__init__(lx, allow=allow, deny=deny,
allow_domains=allow_domains, deny_domains=deny_domains,
restrict_xpaths=restrict_xpaths, restrict_css=restrict_css,
canonicalize=canonicalize, deny_extensions=deny_extensions,maxpages=maxpages) #added maxpages
def extract_links(self, response):
base_url = get_base_url(response)
if self.restrict_xpaths:
docs = [subdoc
for x in self.restrict_xpaths
for subdoc in response.xpath(x)]
else:
docs = [response.selector]
all_links = []
for doc in docs:
links = self._extract_links(doc, response.url, response.encoding, base_url)
links = links[0:self.max_pages] #added maxpages
all_links.extend(self._process_links(links))
return unique_list(all_links)
除了我评论#added maxpages
的地方之外的所有内容都与LxmlLinkExtractor
Scrapy 在lxmlhtml.py
. 我得到的错误是:
"TypeError: object.__init__() takes exactly one argument (the instance to initialize)"
解决方案
super(FilteringLinkExtractor, self)
→super(LimitedLinkExtractor, self)
推荐阅读
- reactjs - React Hooks如何在setState线性完成后调用函数
- c# - 如何验证 JSON 请求中的重复键值
- snowflake-cloud-data-platform - 提高雪管速度以处理每个文件 1 条记录
- amazon-web-services - AWS + Sagemaker Neo 中的对象检测
- styles - litElement 在静态样式中使用类变量
- python - 无法显示带有单击入口点的 Python 二进制 PEX 版本
- python - 多处理问题:函数调用
- javascript - 使用角度附近的删除按钮选择多个文件
- android - Roomdb - 在实体中更新 @Embedded 对象
- amazon-web-services - AWS SES 退回电子邮件但不触发 AWS SNS 退回订阅和主题