我已经为web抓取编写了一个简单的python脚本:
import requests
from bs4 import BeautifulSoup
for i in range(1,3):
url = "https://www.n11.com/telefon-ve-aksesuarlari/cep-telefonu?m=Samsung&pg="+str(i)
html = requests.get(url).content
soup = BeautifulSoup(html, "html.parser")
list = soup.find_all("li",{"class":"column"})
for li in list:
name = li.div.a.h3.text.strip()
print(name)
link = li.div.a.get("href")
oldprice = li.find("div",{"class":"proDetail"}).find_all("a")[0].text.strip().strip('TL')
newprice = li.find("div",{"class":"proDetail"}).find_all("a")[1].text.strip().strip('TL')
print(f"name: {name} link: {link} old price: {oldprice} new price: {newprice}")
它在newprice = li.find("div",{"class":"proDetail"}).find_all("a")[1].text.strip().strip('TL')
行中给了我一个list index out of range
错误
为什么我会犯这个错误?我怎样才能修好它
如上所述,您的代码返回的元素没有预期的那么多
newprice = li.find("div",{"class":"proDetail"}).find_all("a")[1].text.strip().strip('TL')
此find_all("a")
仅返回1<a>
标记的列表此外,您应该检查发生这种情况的网页。我的意思是
当
i=1
或i=2
同时发生时,代码也可能失败。所以你也应该检查每个网页相关问题 更多 >
编程相关推荐