Python爬虫代码错误分析及改进:异常处理、线程池优化
Python爬虫代码错误分析及改进:异常处理、线程池优化
以下代码示例展示了常见的Python爬虫代码错误,并提供了改进方案。
原始代码:
import re
import requests
from bs4 import BeautifulSoup
from concurrent.futures import ThreadPoolExecutor
url = 'https://www.example.com/'
session = requests.Session()
session.headers.update({'User-Agent': 'Mozilla/5.0'})
response = session.get(url, timeout=10)
html = response.text
soup = BeautifulSoup(html, 'html.parser')
keywords = ['{typePython', '{type', '爬虫']
pattern = '|'.join(keywords)
regex = re.compile(pattern)
result = regex.search(html)
if result:
print(result.group())
links = soup.find_all('a')
with ThreadPoolExecutor(max_workers=10) as pool:
responses = pool.map(session.get, (link.get('href') for link in links if link.get('href').startswith('http')), timeout=10)
for response in responses:
sub_html = response.text
sub_results = regex.findall(sub_html)
for sub_result in sub_results:
print(sub_result)
存在的问题:
- 没有对请求异常进行捕获处理,可以使用try-except语句进行处理。
- 在使用ThreadPoolExecutor时,如果子线程请求出现异常,主线程无法获取异常信息,需要在子线程中捕获异常并将异常信息返回给主线程。
- 线程池中的max_workers参数可以根据实际情况进行调整,过高会占用过多系统资源,过低会影响爬虫效率。
改进后的代码:
import re
import requests
from bs4 import BeautifulSoup
from concurrent.futures import ThreadPoolExecutor
url = 'https://www.example.com/'
session = requests.Session()
session.headers.update({'User-Agent': 'Mozilla/5.0'})
try:
response = session.get(url, timeout=10)
response.raise_for_status()
html = response.text
soup = BeautifulSoup(html, 'html.parser')
keywords = ['{typePython', '{type', '爬虫']
pattern = '|'.join(keywords)
regex = re.compile(pattern)
result = regex.search(html)
if result:
print(result.group())
links = soup.find_all('a')
with ThreadPoolExecutor(max_workers=5) as pool:
futures = [pool.submit(session.get, link.get('href'), timeout=10) for link in links if link.get('href').startswith('http')]
for future in futures:
try:
response = future.result()
response.raise_for_status()
sub_html = response.text
sub_results = regex.findall(sub_html)
for sub_result in sub_results:
print(sub_result)
except (requests.exceptions.RequestException, Exception) as e:
print(e)
except (requests.exceptions.RequestException, Exception) as e:
print(e)
改进说明:
- 使用
try-except语句捕获请求异常,并使用response.raise_for_status()方法检查响应状态码,以便更准确地判断请求是否成功。 - 在子线程中使用
try-except语句捕获异常,并将异常信息通过future.result()方法返回给主线程。 - 将线程池中的
max_workers参数设置为5,根据实际情况进行调整。
总结:
通过对代码进行异常处理和线程池优化,可以提高爬虫程序的稳定性和效率。建议根据实际需求调整线程池参数,并使用try-except语句捕获异常,避免程序崩溃。
原文地址: https://www.cveoy.top/t/topic/loMr 著作权归作者所有。请勿转载和采集!