Python、网页抓取和 BeautifulSoup 但不起作用

时间:2021-03-29 08:23:14

标签: python python-3.x web-scraping beautifulsoup python-requests

我想从以下 html 代码中抓取所有产品的列表,以及它们是“有货”还是“缺货”。

<div class="js-product-sizer sizes__layout built" data-scope="conversion-zone">   
            <div class="sizes__wrapper sizes__wrapper--visible" data-id="1042303" data-sellableonline="true">
              <span class="sizes__button sizes__button--selected" role="button" data-quantity="">Taglia</span>
              <ul class="sizes__list" role="listbox">
                  <li class="sizes__size" data-id="969834" data-belowthreshold="false" data-quantity="true" data-available-quantity="1631" data-backinstockqualified="false" data-locale="it" data-storeprice="€1,49" data-storename="Cavallino, Lecce" data-price="1.49" data-weight="0.528" data-favstore-stock="10" data-favstore-above-threshold="false" data-favstore-cnc1h="true" aria-labelledby="size-selector-title" role="option">
                    <span class="sizes__info" data-tnr-size-selector-bootstrap-by-text="">0,5 KG</span>
                    <span class="sizes__stock"                                                             
                                  <span class="sizes__stock__info" data-tnr-size-selector-stock-info="">Disponibile</span>                        
                    </span>
                  </li>
                
                  <li class="sizes__size" data-id="969842" data-belowthreshold="false" data-quantity="false" data-available-quantity="0" data-backinstockqualified="true" data-locale="it" data-storeprice="€3,49" data-storename="Cavallino, Lecce" data-price="3.49" data-weight="1.074" data-displayname="Disco ghisa bodybuilding 28mm" data-favstore-stock="0" data-favstore-above-threshold="false" data-favstore-cnc1h="false" aria-labelledby="size-selector-title" role="option">
                    <span class="sizes__info" data-tnr-size-selector-bootstrap-by-text="">1 KG</span>
                    <span class="sizes__stock">   
                              <span class="sizes__stock__info sizes__stock__info--nostock" data-tnr-size-selector-stock-info="">0 disponibili</span>
                            

我已经运行了以下代码:

import requests
from bs4 import BeautifulSoup
import time

r = requests.get('https://www.decathlon.it/p/disco-ghisa-bodybuilding-28mm/_/R-p-7278?mc=1042303&c=NERO')
soup = BeautifulSoup(r.text, 'html.parser')

for anchor_tag in soup.find_all(class_="js-product-sizer sizes__layout built")[0].findChildren():
    if "sizes_stock" in anchor_tag['class']:
        print(f"Size {anchor_tag.text} OOS")
    else:
        print(f"Size {anchor_tag.text}  in stock!")

但它给了我以下错误:

IndexError: list index out of range

2 个答案:

答案 0 :(得分:1)

如前所述,他们有一种检测自动过程以提取信息的方法。如果您使用 selenium 访问页面 a,它确实会显示 html。所以你可以使用selenium来获取页面源码,然后就可以解析了。

也在那里清理了你的逻辑。无论是否有可用数量,您都在打印 'in stock'

另外,如果您在使用 soup.find_all(class_="js-product-sizer sizes__layout built")[0] 时只想拉取第一个元素 (find_all()),不妨简单地使用 find(),因为这正是它返回的内容,它找到的第一个元素。

代码:

from selenium import webdriver
from bs4 import BeautifulSoup
import time

url = 'https://www.decathlon.it/p/disco-ghisa-bodybuilding-28mm/_/R-p-7278?mc=1042303&c=NERO'


while True:

    driver = webdriver.Chrome(executable_path=r'C:/chromedriver_win32/chromedriver.exe')

    meta = 'ROBOTS'
    while meta == 'ROBOTS':
        driver.get(url)
        page = driver.page_source 
        soup = BeautifulSoup(page,'html.parser')
        if 'name' in soup.find('meta').attrs:
            meta = soup.find('meta')['name']
        else:
            meta = False
        
    driver.close()

    anchor_tag = soup.find(class_="js-product-sizer sizes__layout built")
    items_list = anchor_tag.find_all('li')
    for item in items_list:
        if item['data-weight'] == '0.528':
            continue
        quantity = item['data-available-quantity']
        itemStr = item.text.split('\n')
        if int(quantity) > 0:
            itemStr.insert(2,quantity)
        itemStr = ' '.join(itemStr).strip()
        if item['data-available-quantity'] == '0':
            print(f"Size {itemStr} OOS")
        else:
            print(f"Size {itemStr}  in stock!")
    
    time.sleep(60)

输出:

Size 0,5 KG 1584  Disponibile  in stock!
Size 1 KG  0 disponibili OOS
Size 2 KG  0 disponibili OOS
Size 5 KG  0 disponibili OOS
Size 10 KG  0 disponibili OOS
Size 20 KG  0 disponibili OOS

答案 1 :(得分:-1)

您可以通过调用查看代码有什么问题

r.raise_for_status()

或手动检查 r.status_code

您会看到 requests.exceptions.HTTPError: 403 Client Error: Forbidden for url:...。因此,您的响应文本中确实没有该类的 div,并且无法获取索引为 0 的元素并引发 IndexError。您尝试抓取的网站正在检测简单的抓取请求,请尝试至少设置一些标头(也许 fake_useragent 可以帮助您)。