代码之家  ›  专栏  ›  技术社区  ›  ihonestlydontKnow

Python(BeautifulSoup)仅1个结果

  •  0
  • ihonestlydontKnow  · 技术社区  · 2 年前

    我知道有类似的问题,我已经尝试过申请,但没有解决我的问题。

    我的问题是,在这个网站上: http://books.toscrape.com/catalogue/page-1.html 共有20个价格,当我试图削价时,我只得到第一个价格,而没有其他19个。

    这是密码

    from bs4 import BeautifulSoup
    import requests
    URL = 'http://books.toscrape.com/catalogue/page-1.html'
    page = requests.get(URL)
    soup = BeautifulSoup(page.content, "html.parser")
    results = soup.find_all("div", class_ = "col-sm-8 col-md-9")
    
    for i in results :
        prices = i.find("p", class_ = "price_color")
        print(prices.text.strip())
        print()
    
    1 回复  |  直到 2 年前
        1
  •  0
  •   007    2 年前

    此代码应该可以工作!

    import requests
    from bs4 import BeautifulSoup
    
    
    URL = 'http://books.toscrape.com/catalogue/page-1.html'
    page = requests.get(URL)
    soup = BeautifulSoup(page.content, 'html.parser')
    
    list_of_books = soup.select(
        # using chrom selector
        '#default > div > div > div > div > section > div:nth-child(2) > ol > li'
    )
    
    for book in list_of_books:
        price = book.find('p', {'class': 'price_color'})
        print(price.text.strip())
    
    

    我刚用了chorme选择器 this is a screenshot of it

    您正在使用 find find_all 在错误的地方。