Python Красивый суп соскоб, Newegg - PullRequest
0 голосов
/ 17 ноября 2018

Я новичок в python и решил, что постараюсь научиться готовить веб-страницы.Поэтому я пытаюсь очистить веб-сайт Newegg для видеокарт, но, похоже, есть некоторые проблемы с ошибками.Все, что я хочу сделать, это взять данные и импортировать их в файл CVS, который я могу просмотреть.но, похоже, что если я это прокомментирую, то получу еще одну ошибку, я, похоже, не смогу это понять.Любая помощь приветствуется!

Файл "webScrape.py", строка 32, в цене = price_container [0] .text.strip ("|") IndexError: список индексов вне диапазона

# import beautiful soup 4 and use urllib to import urlopen
import bs4
from urllib.request import urlopen as uReq
from bs4 import BeautifulSoup as soup

# url where we will grab the product data
my_url = 'https://www.newegg.com/Product/ProductList.aspxSubmit=ENE&DEPA=0&Order=BESTMATCH&Description=graphics+card&ignorear=0&N=-1&isNodeId=1'

# open connection and grab the URL page information, read it, then close it
uClient = uReq(my_url)
page_html = uClient.read()
uClient.close()

# parse html from the page
page_soup = soup(page_html, "html.parser")

# find each product within the item-container class
containers = page_soup.findAll("div",{"class":"item-container"})

# write a file named products.csv with the data returned
filename = "products.csv"
f = open(filename, "w")

# create headers for products
headers = "price, product_name, shipping\n"

f.write("")

# define containers based on location on webpage and their DOM elements
for container in containers:
       price_container = container.findAll("li", {"class":"price-current"})
       price = price_container[0].text.strip("|")

       title_container = container.findAll("a", {"class":"item-title"})
       product_name = title_container[0].text

       shipping_container = container.findAll("li",{"class":"price-ship"})
       shipping = shipping_container[0].text.strip()

        f.write(price + "," + product_name.replace(",", "|") + "," + shipping + "\n")

f.close()

1 Ответ

0 голосов
/ 17 ноября 2018

Вы можете записать данные в фрейм данных, и это легко экспортировать в CSV.Я добавил дополнительный селектор классов от .list-wrap до titles, чтобы обеспечить одинаковую длину всех списков.

from bs4 import BeautifulSoup
import requests
import re
import pandas as pd

def main():

    url = 'https://www.newegg.com/Product/ProductList.aspx?Submit=ENE&DEPA=0&Order=BESTMATCH&Description=+graphics+cards&N=-1&isNodeId=1'
    res = requests.get(url)
    soup = BeautifulSoup(res.content, "lxml")
    prices = soup.select('.price-current')
    titles = soup.select('.list-wrap .item-title')
    shipping = soup.select('.price-ship')   
    items = list(zip(titles,prices, shipping))   
    results = [[title.text.strip(),re.search('\$\d+.\d+',price.text.strip()).group(0),ship.text.strip()] for title, price,ship in items]

    df = pd.DataFrame(results,columns=['title', 'current price', 'shipping cost'])
    df.to_csv(r'C:\Users\User\Desktop\Data.csv', sep=',', encoding='utf-8',index = False )

if __name__ == "__main__":
    main()
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...