试图找出我的网络收集器不起作用

问题描述 投票:0回答:1

我是这个项目的编码(Python)新手。

只是想为 eBay 制作一个网络爬行机器人。 我在网上得到了其他网上商店的原始代码,虽然需要进行大量编辑,但我制作了可以在其他网上商店使用的原始版本!这是一次胜利。但 eBay 的结构不同,我需要为 eBay.ca 进行编辑。 (一定是个简单的工作!)我审阅编辑了一整天,最后没找到哈哈。

这是ebay抓取的代码。

#如果我需要在这一行进行解释,它将一一搜索search_string并将信息(日期,名称,价格,运费)保存在csv上。

from bs4 import BeautifulSoup
from urllib import parse
import datetime
import requests
import utils
import time
import random
import re

# result file goes
out_path = 'EBout/'

global_url_path = 'http://www.ebay.ca/'

# timeout
request_get_timeout = 5 # sec

# search
search_string = [
    'ipad10'
    'ipad11'
]

def get_price(html, current_filtter):        
    soup = BeautifulSoup(html, 'lxml')
    #with open(out_path + '_' +'full_content.html',  "w", encoding='utf-8') as fp_full_content:
        #fp_full_content.write(str(soup))

    item_count = 0  # Counter to keep track of imported items

    for item in soup.find_all('div', {'class': 's-item__info clearfix'}):

        # title
        item_name = item.find(class_="s-item__title").find('span').get_text(strip=True)
        # price
        item_price = item.find('span', {'class': 's-item__price'}).get_text(strip=True)
        # shipping price
        item_shipping = item.find(class_='s-item__shipping s-item__logisticsCost').get_text(strip=True)
         
        # title collect
        title = item_name[0]

        # price collect 
        price_text = item_price[0]
        temp_price = re.sub(r'[^0-9.]', '', price_text)
        
        if not temp_price.replace('.', '', 1).isdigit():
            continue
        price = float(temp_price)

        item_shipping_text = item_shipping[0]
        temp_shipping_price = re.sub(r'[^0-9.]', '', item_shipping_text)
        if not temp_shipping_price.replace('.', '', 1).isdigit():
            continue
        shipping = float(temp_shipping_price)

        # date today
        now = datetime.datetime.now().strftime('%Y-%m-%d')


        # csv format
        info  = '{0},"{1}",{2},{3}\n'.format(now, title, price, shipping)
        
        # save into csv 
        with open(out_path + 'EBprice.csv',  "a", encoding='utf-8') as fp:
            fp.write(info)
            print(info)
        
        item_count += 1  # Increment the item counter
        if item_count >= 3:  # Stop importing after x items
            break        

        
if __name__ == '__main__':  
    if not utils.check_out_folder():
        exit(-1)
    headers = {
            "Accept": "application/json, text/javascript, */*; q=0.01",
            "Accept-Encoding": "gzip, deflate, br",
            "Accept-Language": "en-CA,en-US;q=0.7,en;q=0.3",
            "User-Agent": "Mozilla/5.0"
    }

    for item in search_string:
        try:
            url = global_url_path + 'sch/i.html?_from=R40&_nkw=' + parse.quote(item) + '&_sacat=0&_sop=15'
            print('collecting' + item)
            result = requests.get(url, headers=headers, timeout=request_get_timeout)
            html = result.content

            get_price(html, item)

        except Exception as e:
            print(e)
        finally:
            random_wait_time = random.uniform(10, 22)
            time.sleep(random_wait_time)

这是utils.py

import errno
import os
import urllib.request
import urllib.parse


def check_folder(folder):
    try:
        if not(os.path.isdir(folder)):
            os.makedirs(os.path.join(folder))
    except OSError as e:
        if e.errno != errno.EEXIST:
            print(folder + ' failed to create the folder.')
            raise
        return False
    return True

def check_out_folder():    
    return check_folder('EBout')

当我启动它时,它只会生成“我正在搜索此项目”和“0” EBout 上未创建 csv,但创建了 _full_content.html。

我认为我可以使用 ChatGPT 来完成,因为我可以在没有 ChatGPT 的情况下编辑一些我需要的脚本,但对我来说,这个项目比我以前复杂得多。

如果原脚本对你有帮助,我也会上传。 我可以获得帮助以使此爬网程序正常工作吗? 感谢您的阅读!

*我尝试做的:它将在search_string中一一搜索多个商品,并将最便宜的(价格+运费)商品的信息(日期、名称、价格、运费)保存在ebay的csv上。

**因为我是新来的,所以我不知道,但我对讨厌删除帖子的社区有一些经验,如果您担心删除信息,这个帖子不会被我自己删除。

python web-crawler
1个回答
0
投票

您需要修复解析变量。您在

item_shipping =
线上出错,并且它超出了
get_price

这是一个稍微修改过的版本,让它保留在

get_price

    # title
    item_name = item.find(class_="s-item__title").find('span').get_text(strip=True)
    # price
    item_price = item.find('span', {'class': 's-item__price'}).get_text(strip=True)
    # shipping price
    try:
        item_shipping = item.find('span', {'class': 's-item__shipping s-item__logisticsCost'}).get_text(strip=True)
    except:
        item_shipping = '0.0'
     
    # title collect
    title = item_name[0]

    # price collect 
    price_text = item_price[1:]
    temp_price = re.sub(r'[^0-9.]', '', price_text)
© www.soinside.com 2019 - 2024. All rights reserved.