没有页面结构知识的Web抓取

Har*_*son 7 python beautifulsoup web-crawler web-scraping

我正在尝试通过编写脚本来教自己一个概念.基本上,我正在尝试编写一个Python脚本,在给定几个关键字的情况下,它将抓取网页,直到找到我需要的数据.例如,假设我想找一份居住在美国的恶意蛇列表.我可能会使用关键字运行我的脚本list,venemous,snakes,US,并且我希望能够相信至少80%的确定它将返回美国的蛇列表.

我已经知道如何实现web spider部分了,我只是想了解如何在不了解页面结构的情况下确定网页的相关性.我研究过网络抓取技术,但他们似乎都假设知道页面的html标签结构.是否有某种算法允许我从页面中提取数据并确定其相关性?

任何指针都将非常感激.我使用PythonurllibBeautifulSoup.

Far*_*eed 5

使用像scrapy这样的爬虫(只是为了处理并发下载),你可以编写一个这样的简单蜘蛛,并且可能从维基百科开始作为一个很好的起点.这个脚本是通过完整的示例scrapy,nltkwhoosh.它将永远不会停止,并将链接索引以供以后搜索使用whoosh 它是一个小型的Google:

_Author = Farsheed Ashouri
import os
import sys
import re
## Spider libraries
from scrapy.spider import BaseSpider
from scrapy.selector import Selector
from main.items import MainItem
from scrapy.http import Request
from urlparse import urljoin
## indexer libraries
from whoosh.index import create_in, open_dir
from whoosh.fields import *
## html to text conversion module
import nltk

def open_writer():
    if not os.path.isdir("indexdir"):
        os.mkdir("indexdir")
        schema = Schema(title=TEXT(stored=True), content=TEXT(stored=True))
        ix = create_in("indexdir", schema)
    else:
        ix = open_dir("indexdir")
    return ix.writer()

class Main(BaseSpider):
    name        = "main"
    allowed_domains = ["en.wikipedia.org"]
    start_urls  = ["http://en.wikipedia.org/wiki/Snakes"]

    def parse(self, response):
        writer = open_writer()  ## for indexing
        sel = Selector(response)
        email_validation = re.compile(r'^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$')
        #general_link_validation = re.compile(r'')
        #We stored already crawled links in this list
        crawledLinks    = set()
        titles = sel.xpath('//div[@id="content"]//h1[@id="firstHeading"]//span/text()').extract()
        contents = sel.xpath('//body/div[@id="content"]').extract()
        if contents:
            content = contents[0]
        if titles: 
            title = titles[0]
        else:
            return
        links   = sel.xpath('//a/@href').extract()


        for link in links:
            # If it is a proper link and is not checked yet, yield it to the Spider
            url = urljoin(response.url, link)
            #print url
            ## our url must not have any ":" character in it. link /wiki/talk:company
            if not url in crawledLinks and re.match(r'http://en.wikipedia.org/wiki/[^:]+$', url):
                crawledLinks.add(url)
                  #print url, depth
                yield Request(url, self.parse)
        item = MainItem()
        item["title"] = title
        print '*'*80
        print 'crawled: %s | it has %s links.' % (title, len(links))
        #print content
        print '*'*80
        item["links"] = list(crawledLinks)
        writer.add_document(title=title, content=nltk.clean_html(content))  ## I save only text from content.
        #print crawledLinks
        writer.commit()
        yield item
Run Code Online (Sandbox Code Playgroud)

这是完成scrapy示例的文件:


Dan*_*n O 3

您基本上是在问“我如何编写搜索引擎”。这……不是小事。

正确的方法是使用 Google(或 Bing、Yahoo!或...)的搜索 API 并显示前 n 个结果。但是,如果您只是在做一个个人项目来教自己一些概念(但不确定这些概念到底是哪些),那么这里有一些建议:

  • 在适当标签(<p>、、<div>等)的文本内容中搜索相关关键字(废话)
  • 使用相关关键字检查是否存在可能包含您要查找的内容的标签。例如,如果您正在寻找事物列表,那么包含<ul><ol>甚至<table>可能是一个不错的候选者
  • 建立同义词词典并在每个页面中搜索关键字的同义词。将自己限制为“美国”可能意味着仅包含“美国”的页面人为地降低排名
  • 保留不在您的关键字集中的单词列表,并为包含最多这些单词的页面提供更高的排名。这些页面(可以说)更有可能包含您正在寻找的答案

祝你好运(你会需要它)!