快速获取到百度搜索结果原始URL,效率提升10000倍
优采云 发布时间: 2021-03-26 21:24快速获取到百度搜索结果原始URL,效率提升10000倍
我想快速获得百度搜索结果的原创URL。一次进入搜索太慢了,所以我写了一个小的采集器。效率提高了10,000倍。抓取百度搜索结果的前30页平均需要关键词。链接花费了不到4秒的时间。
1、您必须准备一些搜索词。在我的环境中,放置了我的搜索词:key_file_path =“ / Users / mac / Desktop / data / cloudbility / Xiangren Crawler / Baidu /搜索词”
因此,您必须在代码中修改此代码作为搜索词文件的路径。
2、您需要安装MongoDB,因为数据将存储在数据库中,或者您可以将其替换为另一个数据库进行存储,例如Mysql。
代码示例:
# -*- coding:utf-8 -*-
'''
读关键词文件,然后百度搜索到关键词前30页的url爬取并保存至MOngoDB
'''
import multiprocessing # 利用pool进程池实现多进程并行
import time
from bs4 import BeautifulSoup # 处理抓到的页面
import json
import requests
import warnings
# 搜索词路径
key_file_path = "/Users/mac/Desktop/data/cloudbility/四周爬虫/百度/搜索词"
# 忽略警告
warnings.filterwarnings('ignore')
import urllib
from pymongo import MongoClient
# 连接MongoDB
conn = MongoClient('localhost', 27017, connect=False)
baidu_url = conn.baidu_url # 数据库名
urls = baidu_url.cache # 表名
urls.remove()
headers = {'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:22.0) Gecko/20100101 Firefox/22.0'} # 定义头文件,伪装成浏览器
def getfromBaidu(key):
url = 'http://www.baidu.com.cn/s?wd=' + urllib.parse.quote(key) + '&pn=' # word为关键词,pn是分页。
# 创建一个进程池 Pool
pool = multiprocessing.Pool(multiprocessing.cpu_count()) # multiprocess.cpu_count() 返回本计算机cpu的数量。
# 循环次数
for num in range(0, 30):
pool.apply_async(geturl, (url, num, key)) # 多进程
pool.close()
# 调用join之前,先调用close函数,否则会出错。执行完close后不会有新的进程加入到pool,join函数会等待所有子进程结束。
pool.join()
def geturl(url, num, key):
path = url + str(num * 10)
response = requests.get(path, timeout=5)
soup = BeautifulSoup(response.text, 'lxml')
tagh3 = soup.find_all('h3')
for h3 in tagh3:
href = h3.find('a').get('href')
baidus_url = requests.get(url=href, headers=headers, allow_redirects=False)
# ALLOW_REDIRECTS. 设置成 false 禁用重定向;request库默是允许重定向,既拿到新的url的状态,所以我需要的第一个url的状态就拿不到了,这时在请求的时候设置参数把允许重定向这个选项关闭
# 这个时候打印状态 response.status_code 是302,如果允许重定向的情况下这个值是200。
real_url = baidus_url.headers['Location'] # 得到网页原始地址
if real_url.startswith('http'): # 字符串开头匹配
if urls.find_one({'SSH-Linux': real_url}) and len(real_url) > 65:
continue
else:
urls.insert({'SSH-Linux': real_url})
if __name__ == '__main__':
url_list = []
with open(key_file_path, "r") as f:
for i in f.readlines():
if i not in url_list:
url_list.append(i)
open(key_file_path, 'w').close()
with open(key_file_path, "a") as f:
for url in url_list:
b = eval(json.dumps(url, ensure_ascii=False))
f.writelines(b)
key_list = []
with open(key_file_path, "r") as f:
for key in f.readlines():
if key not in key_list and key != "-":
st = time.time()
print('本次采集的关键字是:', key)
getfromBaidu(key)
print('数据库中的条数:', urls.count())
print('本次耗时:', time.time() - st)
运行结果:
/Library/Frameworks/Python.framework/Versions/3.6/bin/python3 /Users/mac/Desktop/data/cloudbility/四周爬虫/百度/1、百度关键词搜索.py
本次采集的关键字是: 齐治 帕拉迪
数据库中的条数: 209
本次耗时: 3.1684470176696777
本次采集的关键字是: 杭州帕拉迪
数据库中的条数: 480
本次耗时: 3.5455269813537598
本次采集的关键字是: 堡垒机, 齐治
省略一万字....
数据库中的条数: 47646
本次耗时: 3.242814302444458
本次采集的关键字是: ucloud堡垒机使用
数据库中存储的数据格式:
(结束)
运维之路-年轻人的运维社区