繁体   English   中英

如何在Python2.7中制作有效的搜寻器

[英]How to make an effective crawler in Python2.7

我正在搜寻一些衣服,以获取它们的价格和每种产品的信息,但是使用我的实际算法,需要几天的时间才能完成,并获得每种产品的每个不同链接。 例如,如果产品具有5种颜色的5个链接,则它具有5个链接,例如,我有一个92k条目和仅5k产品的数据库,如下所示:

https://i.gyazo.com/410d4faa33e2fbccf8979c5399856dd3.png

https://i.gyazo.com/b6118e67205d153272df001fb5efcfc8.png

产品ID相同(产品相同),但链接不同。

因此,我想要一些想法以及如何实现这些想法,例如,我拥有产品ID,因此,如果我已经访问了一个包含该ID的链接,那么我就不想再得到它。 我想抓取所有网络,但只访问那些包含产品的网站...但是我不知道如何实现这两个想法:/

这是我目前的代码(太慢了,重复了很多):

import urllib
import urlparse
from itertools import ifilterfalse
from urllib2 import URLError, HTTPError

from bs4 import BeautifulSoup

urls = {"http://www.kiabi.es/"}
visited = set()


def get_html_text(url):
    try:
        return urllib.urlopen(current_url.encode('ascii','ignore')).read()
    except (IOError,URLError, HTTPError, urllib.ContentTooShortError):
        print "Error getting " + current_url
        urls.add(current_url)


def find_internal_links_in_html_text(html_text, base_url):
    soup = BeautifulSoup(html_text, "html.parser")
    links = set()
    for tag in soup.findAll('a', href=True):
        url = urlparse.urljoin(base_url, tag['href'])
        domain = urlparse.urlparse(base_url).hostname
        if domain in url:
            links.add(url)
    return links


def is_url_already_visited(url):
    return url in visited


while urls:
  try:
    word = '#C'
    current_url = urls.pop()
    print "Parsing", current_url
    if word in current_url:


        print "Parsing", current_url
        htmltext= urllib.urlopen(current_url).read()
        soup= BeautifulSoup(htmltext)

        [get the product info and save it into a sql database]

    html_text = get_html_text(current_url)
    visited.add(current_url)
    found_urls = find_internal_links_in_html_text(html_text, current_url)
    new_urls = ifilterfalse(is_url_already_visited, found_urls)
    urls.update(new_urls)

except Exception:
    pass  

例如,在该搜寻器中,我使用单词“ #C”知道它是一个产品页面并获取其信息,但是我不知道如何区分该url是否具有我已经访问过的产品ID,以及我不知道如何避免不相关的网址,这就是为什么程序速度太慢并获得大量相等链接的原因

感谢您的帮助,您可以改善的所有事情都会很棒^^

我建议使用Scrapy 我的回答是基于它的强大功能。

提出您的疑问:


我不知道如何避免不相关的网址

答:为了避免访问不相关的URL,您应该根据用例使用具有特定逻辑的爬网程序。 也就是说,您可以使用CrawlSpider并定义自己的爬网规则 ,其中每个规则都定义了用于爬网站点的特定行为,因此您将不会访问不相关的URL。

这是一个示例: http : //doc.scrapy.org/en/latest/topics/spiders.html#crawlspider-example


...但是我不知道该网址是否具有我已经访问过的产品ID ...

答:默认情况下,Scrapy使用RFPDupeFilter作为其DUPEFILTER_CLASS ,用于检测和过滤重复的请求。 RFPDupeFilter使用scrapy.utils.request.request_fingerprint函数基于请求指纹进行过滤。

这是重复请求的Scrapy日志输出示例:

2015-11-23 14:26:48 [scrapy] DEBUG: Filtered duplicate request: <GET http://doc.scrapy.org/en/latest/topics/request-response.html> - no more duplicates will be shown (see DUPEFILTER_DEBUG to show all duplicates)

如果您尚未使用它,请参阅以下Scrapy教程: http ://doc.scrapy.org/en/latest/intro/tutorial.html

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM