Python爬虫代码优化:提高运行速度并修复错误
Python爬虫代码优化:提高运行速度并修复错误
以下代码片段展示了一个简单的Python爬虫,用于从网页中提取特定关键词。然而,该代码存在一些错误,并且运行速度也不尽如人意。
代码错误
-
keywords变量中的字符串缺少逗号,应该是keywords = ['{typePython', '{type', '爬虫'] -
在
ThreadPoolExecutor中,如果max_workers设为 10,那么最多同时只会有 10 个请求在执行,但是如果有更多的链接需要请求,它们会被添加到futures列表中等待执行。这可能导致内存占用过高,因此应该使用map方法来并发执行链接请求,而不是将所有的链接放入一个列表中。
优化建议
-
使用
requests.get代替session.get,因为session对象在这个程序中没有任何作用。这样可以避免创建一个不必要的对象。 -
使用
re.search代替soup.find_all(text=regex),因为re.search可以在文本中找到第一个匹配项后就停止搜索,而soup.find_all则会遍历整个文档。这样可以提高代码的运行速度。 -
使用
concurrent.futures.ThreadPoolExecutor.map方法代替ThreadPoolExecutor.submit和as_completed,因为map方法可以将任务分配给线程池,并等待所有任务完成。这样可以使代码更简洁。
修改后的代码
import re
import requests
from bs4 import BeautifulSoup
from concurrent.futures import ThreadPoolExecutor
url = 'https://www.example.com/'
response = requests.get(url)
html = response.text
soup = BeautifulSoup(html, 'html.parser')
keywords = ['{typePython', '{type', '爬虫']
pattern = '|'.join(keywords)
regex = re.compile(pattern)
for keyword in keywords:
result = regex.search(html)
if result:
print(result.group())
links = soup.find_all('a')
with ThreadPoolExecutor(max_workers=10) as pool:
results = pool.map(requests.get, (link.get('href') for link in links if link.get('href').startswith('http')))
for result in results:
sub_html = result.text
sub_result = regex.search(sub_html)
if sub_result:
print(sub_result.group())
通过以上修改,代码可以有效地解决错误,并提高运行速度。建议在实际应用中根据具体情况进行调整和优化。
原文地址: https://www.cveoy.top/t/topic/loLD 著作权归作者所有。请勿转载和采集!