代码之家  ›  专栏  ›  技术社区  ›  Ben P

用Python和BeautifulSoup搭便车

  •  0
  • Ben P  · 技术社区  · 8 年前

    我是Python新手,正在尝试编写一些代码来从网站上获取信息。我目前有:

    from bs4 import BeautifulSoup
    import requests
    
    headers = {'User-Agent': 'Mozilla/5.0'}
    
    for i in range(1, 300):
        url = "[REMOVED]/footwear?page=%s" % i
    
    response = requests.get(url, headers=headers)
    soup = BeautifulSoup(response.text, "html.parser")
    items = soup.find_all('div', 'product-block__info')
    for item in items:
        for val in item.find_all('a','product-block'):
            stock = item.find_all('class','count_product_stock hidden')[0].text
            brand = item.find_all('div','brand')[0].text
            price = item.find_all('span','selling_price')[0].text
    
        print (items)
    

    IndexError: list index out of range . 如果我把“product-block\u info”放在“product block”的位置,那么我就可以打印出页面上“product-block\u info”标签内内容的完整列表,但我只想选择几个元素并返回这些元素。

    有人能解释一下这里发生了什么,以及我如何从“product-block\u info”中选择我想要的元素吗?

    1 回复  |  直到 8 年前
        1
  •  1
  •   t.m.adam    8 年前

    使用选择属性时 find_all 您应该使用 attrs keyword arguments 否则 bs4 正在查找标签。

    for i in range(1, 300):
        url = "[REMOVED]/footwear?page=%s" % i
        response = requests.get(url, headers=headers)
        soup = BeautifulSoup(response.text, "html.parser")
        items = soup.find_all('div', class_='product-block__info')
        for item in items:
            stock = item.find('span', class_='count_product_stock hidden').text
            brand = item.find('h4', class_='brand').text
            price = item.find('span', class_='selling_price').text
            print(stock, brand, price)