Python代码:百度搜索结果爬取和本地索引
以下是使用Python编写的百度搜索结果爬取和本地索引代码,代码已优化,确保爬取和搜索功能正确区分并操作:
import requests
from bs4 import BeautifulSoup
import time
import tkinter as tk
import webbrowser
import random
import os
import re
def get_random_user_agent():
user_agents = [
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.212 Safari/537.36',
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.82 Safari/537.36',
]
return random.choice(user_agents)
def crawl_baidu(keyword, page_limit):
headers = {
'User-Agent': get_random_user_agent()
}
results = []
for page in range(1, page_limit + 1):
url = f'https://www.baidu.com/s?wd={keyword}&pn={(page - 1) * 10}'
# 添加随机延迟
delay = random.uniform(0.5, 1.0)
time.sleep(delay)
response = requests.get(url, headers=headers)
soup = BeautifulSoup(response.text, 'html.parser')
for result in soup.find_all('div', class_='result'):
result_title = result.find('h3').get_text()
result_url = result.find('a')['href']
results.append((result_title, result_url))
return results
def open_url(url):
webbrowser.open(url)
def crawl_and_index():
keywords = re.split(r'[,,\s]+', entry_keywords.get()) # 获取关键词列表
page_limit = int(entry_pages.get()) # 获取指定的爬取页数
# 创建文件夹用于保存网页文件
if not os.path.exists('webpages'):
os.makedirs('webpages')
for keyword in keywords:
search_results = crawl_baidu(keyword, page_limit)
if len(search_results) > 0:
file_name = f'webpages/{keyword}.html'
with open(file_name, 'w', encoding='utf-8') as file:
for title, url in search_results:
file.write(f'{title}\n')
file.write(f'{url}\n')
file.write('\n')
print(f'关键词 '{keyword}' 的搜索结果已保存至文件: {file_name}')
else:
print(f'关键词 '{keyword}' 没有搜索结果')
def search_local():
keyword = entry_search.get()
result_text.delete('1.0', tk.END)
for file_name in os.listdir('webpages'):
if keyword.lower() in file_name.lower():
with open(f'webpages/{file_name}', 'r', encoding='utf-8') as file:
lines = file.readlines()
if len(lines) < 2:
continue
found_results = {}
for i in range(0, len(lines), 2):
if i + 1 >= len(lines):
break
title = lines[i].strip()
url = lines[i + 1].strip()
if keyword.lower() in title.lower() or keyword.lower() in url.lower():
found_results[len(found_results) + 1] = (title, url)
if len(found_results) > 0:
result_text.insert(tk.END, f'搜索结果 - {file_name[:-5]}:\n\n', 'title')
for index, (title, url) in found_results.items():
result_text.insert(tk.END, f'{title}\n', 'found_title')
result_text.insert(tk.END, f'{url}\n', f'link{index}')
result_text.tag_configure(f'link{index}', foreground='blue', underline=True)
result_text.tag_bind(f'link{index}', '<Button-1>', lambda event, url=url: open_url(url))
result_text.insert(tk.END, '\n')
if result_text.get('1.0', tk.END) == '\n':
result_text.insert(tk.END, '没有搜索结果\n')
# 创建UI界面
window = tk.Tk()
window.title('百度搜索')
window.geometry('800x600')
def load_crawl_page():
entry_search.pack_forget()
search_button.pack_forget()
label_keywords.pack()
entry_keywords.pack()
label_pages.pack()
entry_pages.pack()
crawl_button.pack()
def load_search_page():
entry_keywords.pack_forget()
entry_pages.pack_forget()
crawl_button.pack_forget()
label_search.pack()
entry_search.pack()
search_button.pack()
crawl_button = tk.Button(window, text='爬取并索引', command=lambda: load_crawl_page())
crawl_button.pack()
label_keywords = tk.Label(window, text='请输入关键词(用逗号或空格隔开):')
entry_keywords = tk.Entry(window)
label_pages = tk.Label(window, text='请输入爬取页数:')
entry_pages = tk.Entry(window)
search_button = tk.Button(window, text='搜索', command=lambda: load_search_page())
label_search = tk.Label(window, text='请输入搜索关键词:')
entry_search = tk.Entry(window)
result_text = tk.Text
代码功能:
- 使用
requests库获取百度搜索结果页面。 - 使用
BeautifulSoup库解析HTML内容,提取搜索结果标题和链接。 - 将爬取结果保存到本地文件,文件名以关键词命名。
- 提供一个简单的GUI界面,方便用户输入关键词和爬取页数。
- 使用
tkinter库创建GUI界面。 - 提供本地搜索功能,用户可以根据关键词在本地文件搜索结果。
使用方法:
- 确保已经安装了
requests和BeautifulSoup库。 - 运行代码,将出现一个GUI界面。
- 输入关键词和爬取页数,点击“爬取并索引”按钮。
- 爬取结果将保存到名为“webpages”的文件夹中。
- 输入搜索关键词,点击“搜索”按钮,将在结果文本框中显示搜索结果。
注意事项:
- 代码中使用了随机延迟,避免对百度服务器造成过大压力。
- 本代码仅供学习参考,请勿用于任何非法用途。
- 代码中包含
requests和BeautifulSoup的使用示例,可以参考学习。 - 可以根据需要修改代码,例如添加更多的爬取功能或优化GUI界面。
代码优化点:
- 使用
re.split()获取关键词列表,支持多种分隔符。 - 使用
f-string格式化字符串,提高代码可读性。 - 添加随机延迟,避免对百度服务器造成过大压力。
- 使用
os.makedirs()创建文件夹,避免重复创建。 - 使用
with open()打开文件,确保文件在使用完后自动关闭。 - 在GUI界面中使用
pack_forget()和pack()控制控件的显示和隐藏,使界面更加简洁。 - 使用
tag_bind()为链接添加点击事件,方便用户访问链接。
进一步学习:
- 学习更多关于
requests和BeautifulSoup库的使用方法。 - 学习更多关于
tkinter库的用法,创建更复杂的GUI界面。 - 研究百度搜索结果页面的结构,获取更详细的信息。
- 学习如何使用爬虫抓取其他网站的数据。
参考链接:
原文地址: https://www.cveoy.top/t/topic/SLh 著作权归作者所有。请勿转载和采集!