【问题标题】:Jumping over elements that have not the same HTML tag while webscraping网页抓取时跳过具有不同 HTML 标签的元素
【发布时间】:2020-07-07 07:30:08
【问题描述】:

我目前正在尝试在网络上抓取两种不同价格之间节省的百分比。我要抓取的第一个元素的 HTML 代码是:

<li class="price-save">
    <span class="price-save-endtime price-save-endtime-current"></span>
    <span class="price-save-endtime price-save-endtime-another" style="display:none;"></span>
    <span class="price-save-label">Save: </span>
    <span class="price-save-dollar"></span>
    <span class="price-save-percent">22%</span>   <----------------------I WANT THIS ONE!
</li>

为此,我在 Python 中编写了以下代码:

try:
    percentage = soup.find('span',class_='price-save-percent').get_text()
except:
    print("Not found")

但是,当我将结果打印到 .csv 文件中时,如果网站的下一个元素不包含 %,那么它会复制结果,直到找到具有百分比的下一个元素。为了更好的理解,请查看网址:https://www.newegg.com/Laptops-Notebooks/SubCategory/ID-32?Tid=6740

你可以看到第一个元素有% Save,第二个也有,但是第三个没有。在.csv 文件中,第三个元素获得第二个元素的保存百分比。这种情况反复发生。相反,我想要一个空白单元格。

【问题讨论】:

    标签: python html web-scraping data-cleaning


    【解决方案1】:

    您需要处理列表中每个项目的 NA 条件。为此,您需要在网格中仅包含相关的 div 项。下面的代码完成这项工作并将所有 price_saved 保存在列表中(如果可用),否则附加 NA-:

    import bs4
    from urllib.request import urlopen as req
    from bs4 import BeautifulSoup as soup
    import csv
    #Link de la pàgina on farem webscraping
    url = 'https://www.newegg.com/Laptops-Notebooks/SubCategory/ID-32?Tid=6740'
    
    #Obrim una connexió amb la pàgina web
    Client = req(url)
    #Offloads the content of the page into a variable
    pagina = Client.read()
    #Closes the client
    Client.close()
    #html parser
    pagina_soup=soup(pagina,"html.parser")
    #grabs each product
    productes = pagina_soup.findAll("div",{"class":"item-container"})
    
     #Obrim un axiu .csv
    #Capçaleres del meu arxiu .csv
    result_file = open("ordinadors.csv",'a',encoding='utf-8',newline='')
     #Escrivim la capçalera
    head = ["Marca","Producte","PreuActual","PreuAnterior","CostEnvio","Rebaixa"]
    writing_csv = csv.DictWriter(result_file, fieldnames=head)
    writing_csv.writeheader()
    
    #Fem un loop sobre tots els productes
    for producte in productes:
    
        #Agafem la marca del producte
        marca_productes = producte.findAll("div",{"class":"item-info"})
        marca = marca_productes[0].div.a.img["title"]
    
        #Agafem el nom del producte
        name = producte.a.img["title"] 
    
        #Preu Actual
        actual_productes = producte.findAll("li",{"class":"price-current"})
        preuActual = actual_productes[0].strong.text
    
        #Preu anterior    
        try:
            #preuAbans = producte.find("li", class_="price-was").next_element.strip()
            preuAbans = producte.find('span',class_='price-was-data').get_text()
            percentage = producte.find('span',class_='price-save-percent').get_text()
        except:
            preuAbans = "NA"
            percentage = "NA"
    
        #Agafem els costes de envio
        costos_productes = producte.findAll("li",{"class":"price-ship"})
        #Com que es tracta d'un vector, agafem el primer element i el netegem.
        costos = costos_productes[0].text.strip()  
    
        #Writing the file
        writing_csv.writerow({"Marca": marca, "Producte": name, "PreuActual": preuActual, "PreuAnterior": preuAbans,"CostEnvio":costos,"Rebaixa":percentage})
    
    result_file.close()  
    

    【讨论】:

    • 执行此操作时,将文件打印到 .csv 时出现以下错误。 TypeError:只能将str(不是“NoneType”)连接到str
    • 我已经修改了帖子。添加了 .csv 文件代码并将变量保存到您的代码中
    • 您为编写 csv 所做的编辑不完整。变量未定义。我建议你给出诸如 marca、name 等变量的值
    • 其他变量工作正常并正确导出到 .csv 文件中。我刚刚添加了所有行,但是当我添加这一行时出现了问题。
    • 如果您提供您实际尝试做的事情的来源,我只能提供帮助
    猜你喜欢
    • 1970-01-01
    • 2020-10-08
    • 2019-12-04
    • 1970-01-01
    • 2021-04-13
    • 2021-12-23
    • 1970-01-01
    • 1970-01-01
    • 2018-07-30
    相关资源
    最近更新 更多