如何解决为什么索引超出范围?
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)
解决方法
带有该选择器的操作 soup.select
输出一个空的 list
,因此没有 elems[0]
。
如前所述,您使用的选择器不正确,因此 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()
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。