【问题标题】:Get information from webpage with the same class names (Python Selenium)从具有相同类名的网页获取信息(Python Selenium)
【发布时间】:2021-10-21 15:16:59
【问题描述】:

我有一个简单的问题,假设可以很容易地解决。 然而,我现在花了一些时间来提取如下所示的四行信息:

see html structure here

我首先尝试访问 <ul _ngcontent-xl-byg-c79="" class="short ng-star-inserted" 项目,然后循环遍历 <li _ngcontent-xl-byg-c79="" class="table-row ng-star-inserted"> 项目,以便将嵌入的信息存储在我的数据框中(列是“Mærke”、“Produkttype”、“Serie”和“Model ')。

我做错了什么?我的问题是四行具有相同的“类”名称,这在所有四个循环中都给了我相同的输出。

这是我的代码:

from selenium import webdriver
import pandas as pd

# Activate web browser: External control

browser = webdriver.Chrome(r'C:\Users\KristerJens\Downloads\chromedriver_win32\chromedriver')

# Get webpage  

browser.get("https://www.xl-byg.dk/shop/knauf-insulation-ecobatt-murfilt-190-mm-2255993")

# Get information

brand= []
product= []
series=[]
model=[]

for i in browser.find_elements_by_xpath("//ul[@class='short ng-star-inserted']/li"):
    for p in i.find_elements_by_xpath("//span[@class='attribute-name']"):
        brand.append(i.find_elements_by_class_name('?').text)
        product.append(i.find_elements_by_class_name('?').text)
        series.append(i.find_elements_by_class_name('?').text)
        model.append(i.find_elements_by_class_name('?').text)

df = pd.DataFrame()

df['brand'] = brand
df['product'] = product
df['series'] = series
df['model'] = model

非常感谢任何帮助!

【问题讨论】:

    标签: python pandas selenium selenium-webdriver


    【解决方案1】:

    尝试如下并确认:

    from selenium import webdriver
    from selenium.webdriver.support.wait import WebDriverWait
    from selenium.webdriver.support import expected_conditions as EC
    from selenium.webdriver.common.by import By
    
    driver = webdriver.Chrome(executable_path="path to chromedriver.exe")
    driver.maximize_window()
    driver.implicitly_wait(10)
    
    driver.get("https://www.xl-byg.dk/shop/knauf-insulation-ecobatt-murfilt-190-mm-2255993")
    
    wait = WebDriverWait(driver,30)
    
    # Cookie pop-up
    wait.until(EC.element_to_be_clickable((By.XPATH,"//button[@aria-label='Accept all' or @aria-label = 'Accepter alle']"))).click()
    
    options = driver.find_elements_by_xpath("//div[@class='row-column']//ul[contains(@class,'short')]/li")
    for opt in options:
        attribute = opt.find_element_by_xpath("./span[@class='attribute-name']").text # Use a "." in the xpath to find element within in an element
        value = opt.find_element_by_xpath("./*[contains(@class,'ng-star-inserted')]").text
        print(f"{attribute} : {value}")
    
    Mærke : Knauf Insulation
    Produkttype : Murfilt
    Serie : ECOBATT
    Materiale : Glasmineraluld
    

    【讨论】:

      猜你喜欢
      • 2017-07-21
      • 1970-01-01
      • 2020-06-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-03
      • 2016-05-21
      相关资源
      最近更新 更多