我有一个抓取网址列表,并扫描它们以获取其他链接,然后查找任何看起来像电子邮件的内容(使用正则表达式),并返回网址/电子邮件地址列表。
我目前在 Jupyter Notebook 中设置了它,因此我可以在测试时轻松查看输出。问题是,它需要永远运行 - 因为我没有限制刮板的深度(每个 URL)。
理想情况下,scraper 最多可以从每个起始 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 方法——这个方法应用正则表达式 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)
当我们调用 process 方法运行 Spider 时,google_urls 列表作为参数传递,path 定义了 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()
对于每个网站,我制作了一个带有列的数据框:[email, link],并将其附加到之前创建的 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 个结果。
有人知道如何限制深度吗?
像这样在你的 Spider 中设置 DEPTH_LIMIT
class MailSpider(scrapy.Spider):
name = 'email'
custom_settings = {
"DEPTH_LIMIT": 5
}
def parse(self, response):
pass
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句