本人零基础,大龄搬砖男自学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个套餐未点击完毕,大神支招啊,
'''
谢谢?