【问题标题】:How to scrape a specific itemprop from a web page with XPath and Selenium?如何使用 XPath 和 Selenium 从网页中抓取特定的 itemprop?
【发布时间】:2021-07-23 03:44:26
【问题描述】:

我正在尝试使用 Python(Selenium、BeautifulSoup 和 XPath)使用等于“description”的 itemprop 来抓取 span,但每次运行代码时,“try”都会失败并打印出“除了”错误。

当我检查页面上的元素时,我确实看到了代码中的元素。

没有得到预期响应的行:

quick_overview = soup.find_element_by_xpath("//span[contains(@itemprop, 'description')]")

【问题讨论】:

    标签: selenium web-scraping xpath beautifulsoup


    【解决方案1】:

    就个人而言,我认为你应该继续使用 selenium

    quick_overview = driver.find_element_by_xpath("//span[contains(@itemprop, 'description')]") 
    

    为该元素添加.text到end以获取文本内容。

    要实际使用汤来解析它,您可能需要先从 selenium 等待条件,所以没有实际意义。

    但是,如果您决定集成 bs4,那么您需要更改您的函数以使用来自 driver.page_source 的实际 html 并对其进行解析,然后切换到 select_one 以获取您的项目。然后确保您从函数返回并分配给新的汤对象。

    from bs4 import BeautifulSoup
    from selenium import webdriver # links w/ browser and carries out actions
    from selenium.webdriver.common.keys import Keys
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.support import expected_conditions as EC
    
    PATH = "C:\Program Files (x86)\chromedriver_win32\chromedriver.exe"
    baseurl = "http://www.waytekwire.com"
    skus_to_find_test = ['WL16-8', 'WG18-12']
    
    driver = webdriver.Chrome(PATH)
    driver.get(baseurl)
    
    def use_driver_current_html(driver):
        soup = BeautifulSoup(driver.page_source, 'lxml')
        return soup
    
    for sku in skus_to_find_test[0]:
        
        search_bar = driver.find_element_by_id('themeSearchText')
        search_bar.send_keys(sku)
        search_bar.send_keys(Keys.RETURN)   
    
        try:
            
            product_url = driver.find_elements_by_xpath("//div[contains(@class, 'itemDescription')]//h3//a[contains(text(), sku)]")[0]
            product_url.click()
            WebDriverWait(driver,10).until(EC.presence_of_element_located((By.XPATH, "//span[contains(@itemprop, 'description')]")))
            soup = use_driver_current_html(driver)
            
            try:
                quick_overview = soup.select_one("span[itemprop=description]").text
                print(quick_overview)
            except:
                print('No Quick Overview Found.')
                
        except:
            print('Product not found.')
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-02
      • 1970-01-01
      • 2019-08-28
      • 1970-01-01
      • 2020-01-01
      相关资源
      最近更新 更多