需要将no_of_mobile转换为整数格式

时间:2016-09-23 08:40:15

标签: python-2.7

需要转换" no_of_mobile"变量为整数格式并使用循环

打印
import requests
import re
from bs4 import BeautifulSoup

request =  requests.get("https://priceraja.com/mobile/brands/").text
soup = BeautifulSoup(request,"html.parser")
mspec = soup.find('ul', attrs = {"class","top-brands"})
list=[]
no_of_mobile=[]
for link in mspec.find_all('li'):
    li=link.getText('li')
    lit =str(li).split("\n")
    litt=lit
    no_of_mobile= litt[1].replace('(', '').replace(')', '')
    print no_of_mobile

1 个答案:

答案 0 :(得分:0)

在这里, 如果您还想要品牌名称,则应修改解析html文件的代码并进行相应的打印。

import requests
import re
from bs4 import BeautifulSoup

request =  requests.get("https://priceraja.com/mobile/brands/").text
soup = BeautifulSoup(request,"html.parser")
mspec = soup.find('ul', attrs = {"class","top-brands"})
list=[]
no_of_mob=[] ## Note the change in list name
for link in mspec.find_all('li'):
    li=link.getText('li')
    lit =str(li).split("\n")
    litt=lit
    no_of_mobile= litt[1].replace('(', '').replace(')', '')
    no_of_mob.append(int(no_of_mobile)) ## appending the values to the list, here type of the object is string.
no_of_mob=sorted(set(no_of_mob), key=lambda x:int(x),reverse=True) ## sorting the converted integer values
print no_of_mob[:5] ## printing top 5 (Highest no of mobiles)