为什么索引超出范围?

2024-09-29 03:26:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试对一些产品进行webscrape,每当我输入代码时都会出现此错误

import bs4, requests

def getFravegaPrice(productUrl):
    res = requests.get(productUrl)
    res.raise_for_status ()

    soup = bs4.BeautifulSoup(res.text, 'html.parser')
    elems = soup.select('#wrapper > div.border-main > div > div > div.col-md-9.col-sm-9.col-xs-12 > div:nth-child(3) > ul > li:nth-child(7) > div')
    return elems[0].text
    
price = getFravegaPrice('https://compragamer.com/index.php?seccion=3&cate=62&nro_max=50')
print ('The price is ' + price) 

Tags: textdivchild产品rescolrequestsprice
2条回答

如前所述,您使用的选择器不正确,因此elems为空。这里有另一种方法来降低商品的价格

from bs4 import BeautifulSoup
import requests

res = requests.get('https://compragamer.com/index.php?seccion=3&cate=62&nro_max=50')
res.raise_for_status()
soup = BeautifulSoup(res.text, 'html.parser')
item_name = "" #Enter item name you are scraping here
for item in soup.find_all("a"):
    if item_name == item.text.strip():
        price = item.parent.parent.find("span", {"class": "products__price-new"}).text.strip()

使用该选择器的操作soup.select输出一个空的list,因此没有elems[0]

相关问题 更多 >