用scrapy刮掉多个域名的最佳方法是什么?

时间:2011-03-31 08:44:48

标签: python screen-scraping scrapy

我有大约10个奇怪的网站,我希望从中获取。其中一些是wordpress博客,他们遵循相同的HTML结构,虽然有不同的类。其他是论坛或其他格式的博客。

我喜欢抓的信息很常见 - 帖子内容,时间戳,作者,标题和评论。

我的问题是,我是否必须为每个域创建一个单独的蜘蛛?如果没有,我如何创建一个通用蜘蛛,允许我通过从配置文件或类似的东西加载选项来刮掉?

我想我可以从一个文件中加载xpath表达式,这个位置可以通过命令行加载,但是在抓取某些域时似乎有一些困难要求我使用正则表达式select(expression_here).re(regex)而有些则没有。

6 个答案:

答案 0 :(得分:1)

我使用以下XPath表达式做同样的事情:

  • '/html/head/title/text()'标题为
  • //p[string-length(text()) > 150]/text()了解帖子内容。

答案 1 :(得分:1)

在scrapy spider中,将allowed_domains设置为域列表,例如:

class YourSpider(CrawlSpider):    
   allowed_domains = [ 'domain1.com','domain2.com' ]

希望有所帮助

答案 2 :(得分:1)

您可以使用空的allowed_domains属性来指示scrapy不要过滤任何异地请求。但在这种情况下,你必须小心,只返回蜘蛛的相关请求。

答案 3 :(得分:1)

我遇到了同样的问题,所以我使用type()

动态创建了蜘蛛类
from scrapy.contrib.spiders import CrawlSpider
import urlparse

class GenericSpider(CrawlSpider):
    """a generic spider, uses type() to make new spider classes for each domain"""
    name = 'generic'
    allowed_domains = []
    start_urls = []

    @classmethod
    def create(cls, link):
        domain = urlparse.urlparse(link).netloc.lower()
        # generate a class name such that domain www.google.com results in class name GoogleComGenericSpider
        class_name = (domain if not domain.startswith('www.') else domain[4:]).title().replace('.', '') + cls.__name__
        return type(class_name, (cls,), {
            'allowed_domains': [domain],
            'start_urls': [link],
            'name': domain
        })

所以说,为' http://www.google.com'创建一只蜘蛛。我只是做 -

In [3]: google_spider = GenericSpider.create('http://www.google.com')

In [4]: google_spider
Out[4]: __main__.GoogleComGenericSpider

In [5]: google_spider.name
Out[5]: 'www.google.com'

希望这有帮助

答案 4 :(得分:0)

如果你使用的是Python,你应该使用BeautifulSoup。它使您能够在页面中查找元素,并使用正则表达式提取文本。

答案 5 :(得分:0)

您可以使用start_request方法!

,然后您还可以为每个URL分配优先级! 然后,您可以传递一些元数据!

以下是有效的示例代码:

async onClick() {
 let result = await this.requestDataAndWait();
 console.log("result:", result);
}

async requestDataAndWait() {  
 return await this.http.getDataAsObservable();
}

我建议您阅读此页面以获取更多信息

https://docs.scrapy.org/en/latest/topics/spiders.html#scrapy.spider.Spider.start_requests

希望这会有所帮助:)

相关问题