限制抓取抓取工具的页面深度

时间:2020-02-11 05:20:16

标签: python scrapy python-requests jupyter-notebook

我有一个抓取器,其中包含一个URL列表,然后扫描它们以查找其他链接,然后它接着查找类似于电子邮件的任何内容(使用REGEX),并返回URL /电子邮件地址列表。 / p>

我目前在Jupyter Notebook中设置了它,因此我可以在测试时轻松查看输出。问题是,它需要永远运行-因为我没有限制刮板的深度(每个URL)。

理想情况下,刮板从每个起始URL最多可以进入2-5页。

这是我到目前为止所拥有的:

首先,我要导入依赖项:

import os, re, csv, scrapy, logging
import pandas as pd
from scrapy.crawler import CrawlerProcess
from scrapy.linkextractors.lxmlhtml import LxmlLinkExtractor
from googlesearch import search
from time import sleep
from Urls import URL_List

我在Jupyter Notebook中设置了关闭使用Scrapy的日志和警告:

logging.getLogger('scrapy').propagate = False

从那里,我从URL文件中提取URL:

def get_urls():
    urls = URL_List['urls']

然后,我安装好了蜘蛛:

class MailSpider(scrapy.Spider):
    name = 'email'
    def parse(self, response):

我在URL内搜索链接。

        links = LxmlLinkExtractor(allow=()).extract_links(response)

然后将URL列表作为输入,一一读取其源代码。

        links = [str(link.url) for link in links]
        links.append(str(response.url))

我将链接从一种解析方法发送到另一种解析方法。 并设置回调参数,该参数定义请求URL必须发送至的方法。

        for link in links:
            yield scrapy.Request(url=link, callback=self.parse_link)        

然后我将URLS传递给parse_link方法-此方法将regex findall应用于查找电子邮件

    def parse_link(self, response):
        html_text = str(response.text)
        mail_list = re.findall('\w+@\w+\.{1}\w+', html_text)
        dic = {'email': mail_list, 'link': str(response.url)}
        df = pd.DataFrame(dic)
        df.to_csv(self.path, mode='a', header=False)

当我们调用流程方法运行Spider时,google_urls列表作为参数传递,路径定义了保存CSV文件的位置。

然后,我将这些电子邮件保存为CSV文件:

def ask_user(question):
    response = input(question + ' y/n' + '\n')
    if response == 'y':
        return True
    else:
        return False

def create_file(path):
    response = False
    if os.path.exists(path):
        response = ask_user('File already exists, replace?')
        if response == False: return 
    with open(path, 'wb') as file: 
        file.close()

对于每个网站,我都创建一个带有以下列的数据框:[电子邮件,链接],并将其附加到以前创建的CSV文件中。

然后,我将它们放在一起:

def get_info(root_file, path):  
    create_file(path)
    df = pd.DataFrame(columns=['email', 'link'], index=[0])
    df.to_csv(path, mode='w', header=True)

    print('Collecting urls...')
    google_urls = get_urls()

    print('Searching for emails...')
    process = CrawlerProcess({'USER_AGENT': 'Mozilla/5.0'})
    process.crawl(MailSpider, start_urls=google_urls, path=path)

    process.start()

    print('Cleaning emails...')
    df = pd.read_csv(path, index_col=0)
    df.columns = ['email', 'link']
    df = df.drop_duplicates(subset='email')
    df = df.reset_index(drop=True)
    df.to_csv(path, mode='w', header=True)

    return df

get_urls()

最后,我定义一个关键字并运行刮板:

keyword = input("Who is the client? ")
df = get_info(f'{keyword}_urls.py', f'{keyword}_emails.csv')

在100个URL列表中,我用电子邮件地址语法获得了44k个结果。

有人知道如何限制深度吗?

1 个答案:

答案 0 :(得分:1)

像这样在您的Spider中设置DEPTH_LIMIT

class MailSpider(scrapy.Spider):
    name = 'email'

    custom_settings = {
        "DEPTH_LIMIT": 5
    }

    def parse(self, response):
        pass