简体   繁体   English

Python 在 excel 中获得第二个循环到第二列

[英]Python get second for loop to second column in excel

So I have a web scraping script from a retail site and I have been scraping names and prices into an excel successfully.所以我有一个来自零售网站的 web 抓取脚本,我已经成功地将名称和价格抓取到 excel 中。 I wanted to create more scripts for other products on the same site as well but am having some trouble.我也想为同一站点上的其他产品创建更多脚本,但遇到了一些麻烦。 Basically in my other scripts I could reach the price by only using 1 container.基本上在我的其他脚本中,我只需使用 1 个容器即可达到价格。 With this however I had to make another container that is deeper because I don't know how to skip div and span classes.但是,有了这个,我不得不制作另一个更深的容器,因为我不知道如何跳过 div 和 span 类。 So I had to make 2 for loops as you see and I get the results I want however when exported to excel it exports everything in the first column only.因此,如您所见,我必须制作 2 个 for 循环,我得到了我想要的结果,但是当导出到 excel 时,它只导出第一列中的所有内容。 It would help if there was a way to skip classes so that I can only use 1 for loop like previously, or a way to manipulate to data so that I move it to the second column.如果有一种方法可以跳过类,这样我只能像以前一样使用 1 for 循环,或者有一种方法来操作数据以便将它移到第二列,那将会有所帮助。

from bs4 import BeautifulSoup as soup 
from urllib.request import urlopen as uReq  
import requests
import os.path

page_url = "https://www.tenniswarehouse-europe.com/catpage-MSNIKE-EN.html"

save_path = 'C:\\Users\\Lefty\\Desktop\\Scrape Excels'


response = requests.get(page_url, cookies={'SMID':'smc_fbIdmC7VmLvxzHBD0pXTqbYo7kSYh69hqcKQ02xE_239306669'})
soup = soup(response.text, 'html.parser')



containers = soup.findAll("div", {"class":"product_wrapper shoe cf"})
containers1 = soup.findAll("div", {"class":"pricing"})


filename = "Nikes Men's Shoes"
completeName = os.path.join(save_path, filename+".csv")
f = open(completeName, 'w')

headers = "Name, Price\n"

f.write(headers)

for container in containers:
    name = container.div.img['alt']
    f.write(name + "," + '\n') 

    
for container1 in containers1:
    price = container1.span.span.text
    f.write(price.replace(",", ".") + '\n')

You can use zip function instead of looping for each separeted container.您可以使用zip function 而不是为每个分离的容器循环。 So you would just have one loop to write the file, like this:因此,您只需一个循环来写入文件,如下所示:

for name_container, price_container in zip(containers, containers1):
    name = name_container.div.img['alt']
    price = price_container.span.span.text.replace(",", ".")

    f.write(name+ "," + price + "\n")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM