抓取 或网络抓取 是一种用于以自动方式从网站提取数据的技术。它包括使用程序或脚本导航网页、提取特定信息(例如文本、图像、产品价格等)并保存。
在这篇文章中,我将教我用来做抓取的过程以及做这件事时要记住的要点。
就我而言,我将在 pccomponentes 中执行scraping 来收集有关笔记本电脑的信息。这些数据将用于创建一个数据集,作为机器学习模型的基础,旨在根据指定的组件预测笔记本电脑的价格。
首先,需要确定脚本应该访问哪个 url 来执行抓取:
完成后,我们将看到搜索结果:
anchor类型的标签(),其中包含有关我们在搜索结果中看到的产品的大量信息。
如果我们查看以下区域,我们将看到几乎所有的产品数据:
但是我们遇到了一个问题:如果你直接访问pccomponentes,它总是要求我们接受cookie策略。因此,我们无法发出 get 请求并
抓取结果,因为我们不会得到任何东西。
因此,我们必须使用selenium来模拟浏览器并能够与其交互。我们首先执行以下操作:
from selenium import webdriver from selenium.webdriver.firefox.options import options from selenium.webdriver.support.ui import webdriverwait from selenium.webdriver.support import expected_conditions as ec from selenium.webdriver.common.by import by options = options() options.headless = true #abrimos el navegador driver = webdriver.firefox(options=options) time.sleep(5) #vamos a la página indicada pccomponentes.com/laptops driver.get(url+str(i)) #esperamos 30 segundos hasta que aparezca el botón de cookies y al aparecer hace clic accept_cookies = webdriverwait(driver, 30).until( ec.presence_of_element_located((by.id, 'cookiesacceptall')) ) accept_cookies.click() #descargamos el html html = driver.page_source
scrape.
然而,我们遇到了另一个问题。当使用 selenium 打开浏览器并发出 2 或 3 个请求时,cloudflare 会限制请求并且不允许我们发出更多请求。因此,我们只能抓取大约 3 个页面,这将是大约 20 台不同的计算机。不足以制作数据集。
我想到的一个解决方案是在本地下载页面并在本地使用 html。完成抓取后,我们可以打开另一个浏览器(等待合理的时间)并下载以下浏览器。
所以我将上面的代码添加到一个函数中,并将其包装在for 中,如下所示:
#función que se conecta a pccomponentes y guarda el html en local def guarda_datos_html(i=0): try: options = options() options.headless = true #abrimos el navegador driver = webdriver.firefox(options=options) time.sleep(5) #vamos a la página indicada pccomponentes.com/laptops driver.get(url+str(i)) #esperamos 30 segundos hasta que aparezca el botón de cookies y al aparecer hace clic accept_cookies = webdriverwait(driver, 30).until( ec.presence_of_element_located((by.id, 'cookiesacceptall')) ) accept_cookies.click() #descargamos el html html = driver.page_source #lo guardamos en local with open(f'html/laptops_{i}.html','w',encoding="utf-8") as document: document.write(html) driver.close() except: print(f'error en página: {i}') for i in range(0,58): guarda_datos_html(i) time.sleep(30)
beautifulsoup,这是一个在scraping中经常使用的包。
由于之前的功能,我们将开发从我们下载的 html 中收集信息的功能。函数看起来像这样:
# Función que abre el HTML guardado con anterioridad y filtra los datos # para guardarlos en un CSV ordenados def get_datos_html(i=0): try: with open(f'laptop_data_actual.csv','a') as ldata: field = ['Company','Inches','Cpu','Ram','Gpu','OpSys','SSD','Price'] writer = csv.DictWriter(ldata, fieldnames=field) with open(f'html/laptops_{i}.html','r',encoding="utf-8") as document: html = BeautifulSoup(document.read(), 'html.parser') products = html.find_all('a') for element in products: pc = element.get('data-product-name') if pc: pc = pc.lower() marca = element.get('data-product-brand') price = element.get('data-product-price') pc_data = pc.split('/') cpu = pc_data[0].split(' ') cpu = buscar_cpu(cpu) gpu = buscar_gpu(pc_data) inches = '.'.join([s for s in re.findall(r'\b\d+\b', pc_data[-1])]) OpSys = bucar_opsys(pc_data, marca) row = { 'Company': marca, 'Inches': inches, 'Cpu': cpu, 'Ram': pc_data[1], 'Gpu': gpu, 'OpSys': OpSys, 'SSD': pc_data[2], 'Price': price } writer.writerow(row) except: print(f'Error en página: {i}')
我在这里给你留下了完整的脚本,以防你想尝试一下!
pc组件刮板
以上就是如何刮的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号