python - 为什么抓取网页的最后一项后出现错误?
问题描述
我制作了一个从 newEgg 检索产品名称和价格的程序,但是在处理网页上的最后一个产品后,我收到一条错误消息“属性错误:'Nonetype' 对象没有属性'强'。我很确定它是一个空指针错误,因为循环正在运行所有网页元素,但是我尝试迭代到 itemContainers-1,以及在 itemcontainers-1 的循环中设置断点,但它仍然不起作用。另外,我应该把 Client.close() 放在最后对吗?
import bs4
#uReq is our arbitrary shorthand for urllib.request
import urllib
from urllib.request import urlopen as uReq
from bs4 import BeautifulSoup as soup
#The URL we plan to use
my_url = 'https://www.newegg.com/'
#uReq(my_url) opens up web client
Client = uReq(my_url)
#uClient.read dumps everything out of the url
html_page = Client.read()
Client.close()
page_soup = soup(html_page, "html.parser")
itemContainers= page_soup.findAll("div", {"class":"item-container"})
for i in range(0,len(itemContainers)):
if i is len(itemContainers)-1:
{
breakpoint
}
#itemTitles is a list of all of the titles found on the web page
itemTitles = page_soup.findAll("a", {"class": "item-title"})
divWithPriceInfo = itemContainers[i].find("ul", "price")
left_Dec = divWithPriceInfo.strong.text
right_Dec = divWithPriceInfo.sup.text
stringStrong = str(left_Dec)
stringSup = str(right_Dec)
print(itemTitles[i].text)
print(stringStrong + stringSup)
解决方案
推荐阅读
- javascript - vue中需要判断一个数组是否为空
- laravel - 防止已经登录的用户在不同的机器上登录
- angular - 即使经过消毒,它也显示不允许加载本地资源-Angular 7
- excel - Excel:如何计算每n个单元格,值是高于还是低于0
- javascript - Javascript:从网络中提取 csv 数据并存储在数组中
- c# - C#,使用 Linq 通过多个条件从 List 获取对象索引
- beautifulsoup - 使用 BeautilfulSoup 在 python 中解析 html 片段
- neo4j - Cypher/neo4j 返回具有共同起点和终点的路径,终点按路径数过滤
- amp-html - 使用客户端过滤器时,AMP-LIST 不会在初始加载时呈现元素
- android - 在安卓工作室中查看