我是编程新手,正在尝试用python构建我的第一个小网络爬虫。你知道吗
目标:抓取产品列表页面-抓取品牌名称、商品名称、原始价格和新价格-保存在CSV文件中
状态:我已经设法获得了品牌名称、商品名称以及原价,并将它们按正确的顺序排列到一个列表中(例如10种产品)。由于所有项目都有一个品牌名称、描述和价格,所以我的代码将它们按正确的顺序放入csv中。你知道吗
代码:
import bs4
from urllib.request import urlopen as uReq
from bs4 import BeautifulSoup as soup
myUrl = 'https://www.zalando.de/rucksaecke-herren/'
#open connection, grabbing page, saving in page_html and closing connection
uClient = uReq(myUrl)
page_html = uClient.read()
uClient.close()
#Datatype, html paser
page_soup = soup(page_html, "html.parser")
#grabbing information
brand_Names = page_soup.findAll("div",{"class": "z-nvg-cognac_brandName-2XZRz z-nvg-cognac_textFormat-16QFn"})
articale_Names = page_soup.findAll ("div",{"class": "z-nvg-cognac_articleName--arFp z-nvg-cognac_textFormat-16QFn"})
original_Prices = page_soup.findAll("div",{"class": "z-nvg-cognac_originalPrice-2Oy4G"})
new_Prices = page_soup.findAll("div",{"class": "z-nvg-cognac_promotionalPrice-3GRE7"})
#opening a csv file and printing its header
filename = "XXX.csv"
file = open(filename, "w")
headers = "BRAND, ARTICALE NAME, OLD PRICE, NEW PRICE\n"
file.write(headers)
#How many brands on page?
products_on_page = len(brand_Names)
#Looping through all brands, atricles, prices and writing the text into the CSV
for i in range(products_on_page):
brand = brand_Names[i].text
articale_Name = articale_Names[i].text
price = original_Prices[i].text
new_Price = new_Prices[i].text
file.write(brand + "," + articale_Name + "," + price.replace(",",".") + new_Price.replace(",",".") +"\n")
#closing CSV
file.close()
问题:我正努力在正确的位置将折扣价格输入csv。不是每件商品都有折扣,我目前看到我的代码有两个问题:
我使用.findAll查找网站上的信息-由于折扣产品少于总产品,我的新产品价格包含的价格较少(例如10种产品的3个价格)。如果我能够将它们添加到列表中,我假设它们会出现在前3行中。如何确保将新的价格添加到正确的产品中?
我得到“索引错误:列表索引超出范围”的错误,我认为这是由于我循环通过10个产品的事实造成的,但是对于新的\u价格,我到达终点比我的其他列表快?这有道理吗?我的假设正确吗?
我非常感谢你的帮助。你知道吗
谢谢你
托尔斯滕
由于某些项没有
'div.z-nvg-cognac_promotionalPrice-3GRE7'
标记,因此无法可靠地使用列表索引。但是,您可以选择所有容器标记(
'div.z-nvg-cognac_infoContainer-MvytX'
),并使用find
选择每个项目上的标记。你知道吗如果您希望每页获取超过24个项目,则必须使用运行js的客户机,如^{} 。你知道吗
脚注:} 库。} 语句。你知道吗
函数和变量的naming conventions是小写加下划线。
读写csv文件时,最好使用^{
处理文件时,可以使用^{
相关问题 更多 >
编程相关推荐