scrapy如何用于提取网站的链接图?

mit*_*hus 7 web-crawler scrapy

给定一个起点URL start(和受理域等一些规则)我想产生一个有向图(V,E),其中的节点V是从到达的页面start,并且有一个弧形(u,v)的E只要存在对页面的超链接u指向到页面v.

有没有一种简单的方法来获得这样的图形scrapy?如果能够更轻松/更好地实现目标,我也会很高兴使用其他开源工具.

小智 16

我不知道任何正在产生你想要的工具或贡献.你必须建立一个scrapy蜘蛛.我可以在这里解释一下必要的步骤:

  • 创建一个scrapy项目并生成一个默认的蜘蛛

    $ scrapy startproject sitegraph
    $ cd sitegraph
    $ scrapy genspider graphspider mydomain.com
    
    Run Code Online (Sandbox Code Playgroud)
  • 这将创建一个包含items.py文件的目录.在此文件中添加以下行

    from scrapy.item import Item, Field
    
    class SitegraphItem(Item):
         url=Field()
         linkedurls=Field()
    
    Run Code Online (Sandbox Code Playgroud)
  • 在spiders目录中你会发现graphspider.py替换它(当然mydomain.com需要替换):

    from scrapy.selector import HtmlXPathSelector
    from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor
    from scrapy.contrib.spiders import CrawlSpider, Rule
    from scrapy.utils.url import urljoin_rfc
    from sitegraph.items import SitegraphItem
    
    class GraphspiderSpider(CrawlSpider):
        name = 'graphspider'
        allowed_domains = ['mydomain.com']
        start_urls = ['http://mydomain/index.html']
    
        rules = (
            Rule(SgmlLinkExtractor(allow=r'/'), callback='parse_item', follow=True),
        )
    
        def parse_item(self, response):
            hxs = HtmlXPathSelector(response)
            i = SitegraphItem()
            i['url'] = response.url
            i['http_status'] = response.status
            llinks=[]
            for anchor in hxs.select('//a[@href]'):
                href=anchor.select('@href').extract()[0]
                if not href.lower().startswith("javascript"):
            llinks.append(urljoin_rfc(response.url,href))
            i['linkedurls'] = llinks
            return i
    
    Run Code Online (Sandbox Code Playgroud)
  • 然后编辑settings.py文件并添加(相应地更改文件名):

    FEED_FORMAT="jsonlines"
    FEED_URI="file:///tmp/sitegraph.json"
    
    Run Code Online (Sandbox Code Playgroud)
  • 现在你可以运行:

    $ scrapy crawl graphspider
    
    Run Code Online (Sandbox Code Playgroud)
  • 这将生成一个json文件,您可以使用它来构建图形.

您可以使用像networkx这样的软件包来分析它的pygraphviz来绘制它(不建议用于大型网站)

import json
import pygraphviz as pg

def loadgraph(fname):
        G=pg.AGraph(directed=True)
        for line in open(fname):
            j=json.loads(line)
            url=j["url"]
            G.add_node(url)
            for linked_url in j["linkedurls"]:
                G.add_edge(url,linked_url)
        return G

if __name__=='__main__':
        G=loadgraph("/tmp/sitegraph.json")
        G.layout(prog='dot')
        G.draw("sitegraph.png")
Run Code Online (Sandbox Code Playgroud)