AttributeError:'int'对象没有属性'replace'python3.x

时间:2018-08-13 07:15:31

标签: python-3.x web-scraping beautifulsoup

我写了一些返回两个输出的代码。出现错误。我的代码的主要问题是什么???????

我从python3.x使用-beautifulsoup4-4.6.3

import codecs
from urllib.request import urlopen as uReq

from bs4 import BeautifulSoup as soup

for i in range(3): #electronic

my_url = "https://www.bamilo.com/mobile_phones/?facet_is_mpg_child=0&viewType=gridView&page="

uClient = uReq(my_url + str(i))

page_html = uClient.read()

uClient.close()

page_soup = soup(page_html, "html.parser")

containers = page_soup.findAll("div" , {"class" : "sku -gallery" })

filename = "mobile.csv"
f = codecs.open(filename, "a" , "utf-8-sig")
headers = "name, Brand, price_one, price_two, ranking\n"
f.write(headers)


for container in containers:

    name = container.img["alt"]

    title_container = container.findAll("span", {"class" : "brand"})

    Brand = title_container[0].text

    price = container.findAll("span",{"class" : "price"} )

    price_one = price[0].text.strip()

    price_old = container.findAll("span",{"class" : "price -old "})
    price_two = 0
    if len(price_old) > 0:
        price_two = price_old[0].text.strip()

    rank = container.findAll("span",{"class" : "rating-aggregate"})
    if len(rank) > 0:
        ranking = rank[0].text.strip()

    print("name " + name)
    print("Brand "+ Brand)
    print("price_one " + price_one)
    print("price_two {}".format(price_two))
    print("ranking " + ranking)

    f.write(name + "," + Brand.replace(",", "|") + "," + price_one.replace(",", "") + "," + price_two.replace(",", "") + "," + ranking + "\n")

f.close()
  

回溯(最近通话最近):   名称Galaxy J7 Pro SM-J730FD Dual 64GB金色     在第53行的“ C:/ Users /...../。PyCharm2018.2 / config / scratches / scratch.py​​”文件中   品牌三星       f.write(name +“,” + Brand.replace(“,”,“ |”)+“,” + price_one.replace(“,”,“”)+“,” + price_two.replace(“,” ,“”)+“,” +排名+“ \ n”)   AttributeError:“ int”对象没有属性“ replace”   price_one 32,050,000ریال   price_two 0   排名1

错误:::::

f.write(name + "," + Brand.replace(",", "|") + "," + 
price_one.replace(",", "") + "," + price_two.replace(",", "") + "," + 
ranking + "\n")

AttributeError: 'int' object has no attribute 'replace'

应进行哪些更改?有什么解决办法吗?

1 个答案:

答案 0 :(得分:0)

由于$(function() { if(localStorage){ $('#toggle-one').prop("checked",localStorage["ck"]==1); } $("#toggle-one").on("change",function(e){ window.localStorage["ck"] = e.target.checked?1:0; }) }) 这行而导致您遇到错误,如果不满足您设置的条件,则price_two = 0的值是一个整数。而且您不能在其上使用price_two

解决问题替换

str.replace

price_two = 0