huang7899135 2018-11-04 14:13 采纳率: 0%
浏览 846

python环境,利用selenium爬取京东手机“每种套餐”价格问题

本人零基础,大龄搬砖男自学python,所以请忽略各种拼写,命名等小细节。而且目前还不会正则表达式,所以用了xpath的方法,循环点击各套餐,然后读取价格标签的text来获取价格。但是因为不同的产品,套餐种类可能不同,例如有点手机品牌有颜色、容量、运行商,版本等套餐。为了考虑多产品的兼容性,折磨了半天时间,想到用递归的思路进行实现
目前,遇到一个问题,就是递归的终止条件问题,目前总是卡在最后一个套餐,没有读取完就结束了。请前辈支招:

 from bs4 import BeautifulSoup
from selenium import webdriver
driver = webdriver.Chrome()
driver.get("https://item.jd.com/100000287115.html#crumb-wrap")
driver.maximize_window()
html = driver.page_source
soup=BeautifulSoup(html,'lxml')
select = soup.find("div",id="choose-attrs") #查找选择框

selectstyle = select.find_all("div",class_="li p-choose") #选择的类型有多少种,比如颜色,型号,容量等
selectstyletotal = len(selectstyle) #大类数量
print(selectstyletotal)

def sonnum(n): #n为大类编号从1开始
    '''求当前大类下面有多少个型号'''
    selectsun = selectstyle[n-1].find_all("div", class_="item")
    countsun = len(selectsun)  # 查找当前类下,有多少个型号
    return countsun

for i in range(1,selectstyletotal+1):
    print("当前为第{}类,改类有{}个型号".format(i,sonnum(i)))

def showprice(n):
    '''递归选择,并显示价格'''
    if n == 1:
        for a in range(1, sonnum(n) + 1):
            driver.find_element_by_xpath(
                '//*[@id="choose-attr-' + str(n) + '"]/div[2]/div[' + str(a) + ']').click()
            select_txt = driver.find_element_by_xpath(
                '//*[@id="choose-attr-' + str(n) + '"]/div[2]/div[' + str(a) + ']').text
            price = driver.find_element_by_xpath(
                "/html/body/div[8]/div/div[2]/div[4]/div/div[1]/div[2]/span[1]/span[2]").text
            # price_data.append(select_txt+"价格为"+price)
            print("选中{},价格为{}".format(select_txt, price))

    for i in range(1,sonnum(n)+1):
        try:
            driver.find_element_by_xpath(
                '//*[@id="choose-attr-' + str(n) + '"]/div[2]/div[' + str(i) + ']').click()
            select_txt = driver.find_element_by_xpath(
                '//*[@id="choose-attr-' + str(n) + '"]/div[2]/div[' + str(i) + ']').text
            print("选中{}".format(select_txt))
            showprice(n-1)
            price = driver.find_element_by_xpath(
                "/html/body/div[8]/div/div[2]/div[4]/div/div[1]/div[2]/span[1]/span[2]").text
        except:
            continue
        print("价格为{}".format(price))
showprice(selectstyletotal)

运行结果如下:始终有1个套餐未点击完毕,大神支招啊,
'''

图片说明

谢谢?

  • 写回答

2条回答 默认 最新

  • devmiao 2018-11-04 14:19
    关注
    评论

报告相同问题?

悬赏问题

  • ¥20 求数据集和代码#有偿答复
  • ¥15 关于下拉菜单选项关联的问题
  • ¥20 java-OJ-健康体检
  • ¥15 rs485的上拉下拉,不会对a-b<-200mv有影响吗,就是接受时,对判断逻辑0有影响吗
  • ¥15 使用phpstudy在云服务器上搭建个人网站
  • ¥15 应该如何判断含间隙的曲柄摇杆机构,轴与轴承是否发生了碰撞?
  • ¥15 vue3+express部署到nginx
  • ¥20 搭建pt1000三线制高精度测温电路
  • ¥15 使用Jdk8自带的算法,和Jdk11自带的加密结果会一样吗,不一样的话有什么解决方案,Jdk不能升级的情况
  • ¥15 画两个图 python或R