我的问题实际上是如何做与上一个问题相同的事情,但在Scrapy 0.14中。
Using one Scrapy spider for several websites
基本上,我有一个图形用户界面,如域,关键字,标签名称等参数,我想创建一个通用的蜘蛛来爬行这些领域的那些关键字在那些标签。我使用旧版本的scrapy,通过覆盖爬行器管理器类或动态创建爬行器,读取了冲突的内容。哪种方法是首选的,我如何实现和调用适当的解决方案?提前谢谢。
下面是我想要泛型的代码。它还使用BeautifulSoup。我对它进行了配对,所以希望没有删除任何关键的东西来理解它。
class MySpider(CrawlSpider):
name = 'MySpider'
allowed_domains = ['somedomain.com', 'sub.somedomain.com']
start_urls = ['http://www.somedomain.com']
rules = (
Rule(SgmlLinkExtractor(allow=('/pages/', ), deny=('', ))),
Rule(SgmlLinkExtractor(allow=('/2012/03/')), callback='parse_item'),
)
def parse_item(self, response):
contentTags = []
soup = BeautifulSoup(response.body)
contentTags = soup.findAll('p', itemprop="myProp")
for contentTag in contentTags:
matchedResult = re.search('Keyword1|Keyword2', contentTag.text)
if matchedResult:
print('URL Found: ' + response.url)
pass
发布于 2012-10-25 01:44:29
您可以创建一个由解释器计算的运行时爬行器。这段代码可以在运行时评估,如下所示:
a = open("test.py")
from compiler import compile
d = compile(a.read(), 'spider.py', 'exec')
eval(d)
MySpider
<class '__main__.MySpider'>
print MySpider.start_urls
['http://www.somedomain.com']
发布于 2012-09-27 16:46:32
与其将变量name
、allowed_domains
、start_urls
和rules
附加到类中,不如编写一个MySpider.__init__
,从中调用CrawlSpider.__init__
,传递必要的参数,并为每个对象设置name
、allowed_domains
等。还应该在__init__
中设置MyProp
和关键字。所以最后你应该会有类似下面这样的东西。您不必将name
添加到参数中,因为name
是由BaseSpider
本身从kwargs
设置的:
class MySpider(CrawlSpider):
def __init__(self, allowed_domains=[], start_urls=[],
rules=[], findtag='', finditemprop='', keywords='', **kwargs):
CrawlSpider.__init__(self, **kwargs)
self.allowed_domains = allowed_domains
self.start_urls = start_urls
self.rules = rules
self.findtag = findtag
self.finditemprop = finditemprop
self.keywords = keywords
def parse_item(self, response):
contentTags = []
soup = BeautifulSoup(response.body)
contentTags = soup.findAll(self.findtag, itemprop=self.finditemprop)
for contentTag in contentTags:
matchedResult = re.search(self.keywords, contentTag.text)
if matchedResult:
print('URL Found: ' + response.url)
发布于 2015-02-17 02:17:08
就搜索作为参数传递的特定域而言,我只是覆盖了Spider.__init__
class MySpider(scrapy.Spider):
"""
This spider will try to crawl whatever is passed in `start_urls` which
should be a comma-separated string of fully qualified URIs.
Example: start_urls=http://localhost,http://example.com
"""
def __init__(self, name=None, **kwargs):
if 'start_urls' in kwargs:
self.start_urls = kwargs.pop('start_urls').split(',')
super(Spider, self).__init__(name, **kwargs)
https://stackoverflow.com/questions/9814827
复制相似问题