加速Google Dork爬虫:代码优化指南
以下内容提供一些建议,帮助您优化 Google Dork 爬虫代码,提高运行速度:
-
使用多进程加速程序运行,可以使用
multiprocessing库。 -
调整线程池的数量,根据机器的性能和网络带宽进行调整。例如,将代码中的
ThreadPoolExecutor(max_workers=20)中的max_workers参数根据实际情况进行修改。 -
使用异步框架,比如
asyncio或者aiohttp,来提高程序的并发能力。异步框架可以有效地处理多个请求,提升程序的效率。 -
考虑使用一些第三方模块,比如
googlesearch-python和googlesearch-api,这些模块已经封装了谷歌搜索的接口,可以直接调用,从而提高程序的运行效率。 -
优化代码逻辑,避免不必要的循环和判断,减少程序的运行时间。比如可以将多个函数合并成一个函数,避免频繁调用函数。
以下是一些具体的代码示例,可以参考:
import requests
import time
import os
import urllib3
import sys
import random
from bs4 import BeautifulSoup
from concurrent.futures import ThreadPoolExecutor
from threading import Lock
from colorama import Fore, init
from multiprocessing import Pool # 引入 multiprocessing 库
now_time = time.strftime('%Y-%m-%d %H-%M')
# 读取Dorks
def work(dorks):
with open(dorks, mode='r', encoding='utf-8') as file:
read_content = file.readlines()
# 将内容加入列表
content = [result.strip() for result in read_content]
# 返回数量丢给任务池
return len(read_content), content
# Google搜索
def google_serach(query, locks, filename):
try:
# 关闭HTTPS报错信息
urllib3.disable_warnings()
filename = os.path.join(os.getcwd(), f'{filename}.txt')
domains = ['fr','it','ca','co.uk','ru','co,jp','co.kr','com.au','co.in','com.br','com.ar','co.za','co.nz','es','se','nl','ch','at','dk','be','pl','fi','ie','pt','gr', 'tw', 'com', 'uk', 'de', 'br', 'ca', 'kr', 'mx', 'au', 'za']
random_domain = random.choice(domains)
url = f'https://www.google.{random_domain}/search?q={query}&num=100'
# 请求头
headers = {
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/111.0.0.0 Safari/537.36',
'accept-language': 'zh-CN,zh;q=0.9',
'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7',
'referer': 'https://www.google.com/',
'origin': 'https://www.google.com',
'Sec-Fetch-Site': 'same-origin',
'Sec-Fetch-Mode': 'navigate',
'Sec-Fetch-User': '?1',
'Sec-Fetch-Dest': 'document'
}
# 代理
proxies = {'http': 'http://127.0.0.1:7890', 'https': 'http://127.0.0.1:7890'}
response = requests.get(url=url, headers=headers, proxies=proxies, verify=False, timeout=5)
soup = BeautifulSoup(response.content, 'html.parser')
# 查找全部div标签
find_div = soup.find_all('div', {'class': 'yuRUbf'})
# 开启线程锁
locks.acquire()
# 加入列表
get_url = [url.findNext('a')['href'] + '\n' for url in find_div if 'google.com.tw' not in url.findNext('a')['href']]
global url_num, dork_finish_num
url_num += len(get_url)
dork_finish_num += 1
print(Fore.GREEN + f'\r{now_time}[INFO]{ '-' * 10}>已获取Url数量:{url_num} Dorsk数量:{dork_finish_num} / {dork_total_num}', end='' + Fore.RESET)
# 写入文件
write_info(filename, get_url)
# 释放线程锁
locks.release()
except TimeoutError:
pass
# 写入文件函数
def write_info(filename, get_url):
with open(filename, mode='a+', encoding='utf-8') as file:
file.writelines(get_url)
if __name__ == '__main__':
while True:
try:
init() # 初始化颜色模块
dorks_file = input(Fore.YELLOW + f'\n{now_time}[INFO]{ '-' * 10}>input file:' + Fore.RESET)
print('')
filename = input(Fore.YELLOW + f'\n{now_time}[INFO]{ '-' * 10}>output file:' + Fore.RESET)
# 接受work函数返回的元组
dork_total_num, query_list = work(dorks_file)
# 定义全局变量完成数量/URL数量
dork_finish_num = url_num = 0
# 使用多进程池
with Pool(processes=4) as pool: # 设置进程数量为 4
pool.map(google_serach, query_list) # 使用 map 函数并行执行
if len(sys.argv) == 1:
pass
input(Fore.YELLOW + f'\n\n{now_time}[INFO]{'-' * 10}>程序运行完毕,按回车退出' + Fore.RESET)
break
# 文件为空
except FileNotFoundError:
print(Fore.RED + f'{now_time}[Error]{'-' * 10}>文件不存在' + Fore.RESET)
# 中断异常
except KeyboardInterrupt:
sys.exit(1)
解释
- 代码示例中使用了
multiprocessing库,创建了Pool对象,设置进程数量为 4,然后使用pool.map函数并行执行google_serach函数,从而加速程序运行。 - 您可以根据机器的性能和网络带宽调整进程数量。
此外,您还可以考虑使用其他方法,比如使用异步框架 asyncio 或者 aiohttp 来提升程序的并发能力。
请注意,以上只是示例代码,您需要根据实际情况进行调整。建议您先进行测试,找到最适合您的优化方法。
原文地址: https://www.cveoy.top/t/topic/oZO2 著作权归作者所有。请勿转载和采集!