【spider】Python爬虫爬取Yohobuy网站数据

本文介绍了一种使用Selenium爬虫抓取有货网鞋靴类商品数据的方法,并通过PyQuery解析网页,最终将数据存储到MongoDB中。文章详细展示了爬虫的实现过程,包括页面加载、元素定位、数据抓取及存储等关键步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

主要使用selenium爬取有货网鞋靴类商品数据,运用mongodb对数据进行存储,数据处理部分参照yohobuy数据处理

#spider.py
from selenium import webdriver
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from pyquery import PyQuery as pq
from config import *
import pymongo

client = pymongo.MongoClient(MONGO_URL)
db = client[MONGO_DB]

browser = webdriver.Chrome()
wait = WebDriverWait(browser, 10)

browser.set_window_size(1400, 900)


def search():
    print('正在搜索')
    try:
        browser.get('https://www.yohobuy.com')
        close = wait.until(
            EC.element_to_be_clickable((By.XPATH, '//*[@id="cover"]/div[2]/a'))
        )
        close.click()
        shoes = wait.until(
            EC.element_to_be_clickable((By.CSS_SELECTOR, '#yoho-header > div.nav-wrapper.clearfix > div > ul.sub-nav-list.boys.cure > li:nth-child(4) > a'))
        )
        shoes.click()
        close1 = wait.until(
            EC.element_to_be_clickable((By.CSS_SELECTOR, 'body > div.product-page.yoho-page.product-list-page.static-list-page > div > div.list-right.pull-right > div.filter-box > div.checked-conditions.section > div > a.tag > i'))
        )
        close1.click()
        total = wait.until((EC.presence_of_element_located((By.CSS_SELECTOR, 'body > div.product-page.yoho-page.product-list-page.static-list-page > div > div.list-right.pull-right > div.sort-pager > div > p > span:nth-child(2)'))))
        get_products()
        return total.text
    except TimeoutException:
        return search()


def next_page(total_page):
    for i in range(2, total_page+1):
        print('正在翻页', i)
        fan = wait.until(
            EC.element_to_be_clickable((By.CSS_SELECTOR, 'body > div.product-page.yoho-page.product-list-page.static-list-page > div > div.list-right.pull-right > div.goods-container.clearfix > div.block-next-page > a > img'))
        )
        get_products()
        fan.click()


def get_products():
    wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, '.product-page .goods-container .good-info')))
    html = browser.page_source
    doc = pq(html)
    items = doc('.product-page .goods-container .good-info').items()
    for item in items:
        product = {
            'url': item.find('.good-thumb').attr('href'),
            'brand': item.find('.brand ').text(),
            'deal': int(item.find('.price').text().split('.')[0][1:]),
            'title': item.find('.good-detail-text').text().split('\n')[0]
        }
        print(product)
        save_to_mongo(product)


def save_to_mongo(result):
    try:
        if db[MONGO_TABLE].insert(result):
            print("存储到MONGODB成功", result)
    except Exception:
        print("保存到MONGODB失败", result)


def main():
    total = search()
    total = int(total[2:])
    next_page(total)
    browser.close()


if __name__ == '__main__':
    main()

#config.py
MONGO_URL = 'localhost'
MONGO_DB = 'yohobuy'
MONGO_TABLE = 'product'

### 使用Python爬虫读取本地计算机数据 要使用Python爬虫读取本地计算机上的数据,可以通过访问本地文件系统来实现。虽然传统意义上的爬虫通常用于从互联网上抓取数据,但也可以通过类似的方式处理本地文件。以下是一个详细的说明: #### 1. 访问本地文件系统 Python 提供了多种方法来读取本地文件系统中的数据。可以使用内置模块如 `os` 和 `glob` 来遍历目录和文件[^1]。 ```python import os import glob # 遍历指定目录下的所有文件 directory_path = "./data" # 替换为你的目标路径 files = glob.glob(os.path.join(directory_path, "*")) for file in files: if os.path.isfile(file): with open(file, "r", encoding="utf-8") as f: content = f.read() print(f"文件 {file} 的内容:") print(content) ``` 上述代码中,`glob` 模块用于匹配文件路径模式,`os.path.isfile` 用于检查是否为文件而不是目录[^2]。 #### 2. 使用正则表达式解析数据 如果需要从本地文件中提取特定格式的数据,可以结合正则表达式进行解析[^5]。例如,假设文件内容包含 HTML 表格结构,可以使用如下代码提取表格中的数据: ```python import re # 假设文件名为 example.html with open("example.html", "r", encoding="utf-8") as f: html_content = f.read() # 使用正则表达式提取表格数据 table_rows = re.findall(r"<tr>.*?</tr>", html_content, re.DOTALL) for row in table_rows: cells = re.findall(r"<td>(.*?)</td>", row) for cell in cells: print(cell.strip(), end=" ") print() ``` #### 3. 使用高级框架(可选) 如果需要更复杂的功能,可以考虑使用 Scrapy 等高级爬虫框架。尽管 Scrapy 主要用于网络爬取,但它也可以处理本地文件[^4]。以下是一个简单的示例: ```python import scrapy class LocalFileSpider(scrapy.Spider): name = "local_file" start_urls = ["file:///path/to/your/local/file.html"] # 替换为你的本地文件路径 def parse(self, response): for row in response.css("tr"): yield { "data": row.css("td::text").getall() } ``` 运行此脚本时,Scrapy 将从指定的本地文件中提取数据,并将其作为字典返回。 #### 注意事项 - 确保对本地文件的操作符合权限要求。 - 如果文件较大,建议分块读取以避免内存溢出[^3]。 - 对于敏感数据,注意保护隐私,避免泄露信息。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值