【发布时间】:2024-05-21 21:55:01
【问题描述】:
我正在尝试使用硒和美丽的汤来解析表格,但我在定位和吸引课程价值时遇到了问题。似乎每一列都有相同的类名,这使得它更加困难。这是我试图解析的 html 代码的一部分:
这是表格的外观:
所以到目前为止我的编码是这样的:
driver = webdriver.Chrome()
driver.get(base_url)
driver.implicitly_wait(100)
driver.find_elements_by_class_name("plp-pod__image")[0].click()
first = driver.find_elements_by_class_name("col-6 specs__cell specs__cell--label")[0].getText()
first
所以基本上我打开 Chrom 浏览器,加载我正在寻找的项目的页面,然后寻找所有名为“col-6 specs__cell specs__cell--label”的类,并尝试从出现的第一个类中获取文本.我正在尝试解决所有 5 个维度及其值的问题。
当我执行我的代码时,我得到了这个错误:
---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
<ipython-input-27-2e124acf6be5> in <module>
3 driver.implicitly_wait(100)
4 driver.find_elements_by_class_name("plp-pod__image")[0].click()
----> 5 first = driver.find_elements_by_class_name("col-6 specs__cell specs__cell--label")[0].getText()
IndexError: list index out of range
知道如何解析这些元素以将所有 5 个维度及其值放入 pandas 数据框吗?
我尝试像这样结合您的两个建议:
from selenium.common.exceptions import NoSuchElementException,
NoSuchFrameException
i = "Marshalltown PT164BR"
base_url = f"https://www.homedepot.com/s/" + i +"?NCNI-5"
driver = webdriver.Chrome()
driver.get(base_url)
WebDriverWait(driver, 5).until(EC.element_to_be_clickable((By.CSS_SELECTOR,
".plp-pod__image"))).click()
#%%
groups = driver.find_elements_by_class_name("specs__group")
data = {}
for group in groups:
if "placeholder" not in group.get_attribute("class"):
specs = group.find_elements_by_class_name("specs__cell")
dimension = specs[0].text.strip()
value = float(specs[1].text.replace("in","").strip())
#print(dimension,":",value)
if dimension not in data:
data[dimension] = []
data[dimension].append(value)
print(data)
data_frame = pd.DataFrame(data=data)
print(data_frame)
然后我进入了我用作测试的网页,以及我用作测试的项目,但它似乎没有读取正确的类,它给了我这个错误:
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-3-1f3f99bc45ee> in <module>
5 specs = group.find_elements_by_class_name("specs__cell")
6 dimension = specs[0].text.strip()
----> 7 value = float(specs[1].text.replace("in","").strip())
8 #print(dimension,":",value)
9 if dimension not in data:
ValueError: could not convert string to float:
【问题讨论】:
标签: python python-3.x selenium-webdriver xpath selenium-chromedriver