import ssl
from urllib.request import urlopen as uReq
from bs4 import BeautifulSoup as soup
context = ssl._create_unverified_context()
def PriceOfLegos(Site):
price = []
title = []
LegoWebsite = Site
uLegoWebsite = uReq(LegoWebsite,context=context)
LegoWebsiteHTML = uLegoWebsite.read()
uLegoWebsite.close()
LegoWebsiteSoup = soup(LegoWebsiteHTML,"html.parser")
for x in LegoWebsiteSoup.find_all("span",{"class": "visuallyhidden"}):
text = x.get_text()
if text[0] == "$":
price.append(text[1:])
for x in LegoWebsiteSoup.find_all("a",{"class": "product-title-link line-clamp line-clamp-2"}):
title_text = x.get_text()
title.append(title_text)
for x in price:
print("$",x,sep="")
z = PriceOfLegos("https://www.walmart.com/search/?query=Lego%20horse")
print(z)
当代码不是函数且LegoWebsite = URL时,抓取有效。唯一的问题是我希望它更具动态性,因此我可以在沃尔玛上输入任何搜索URL,它会显示价格。我面临的问题是当我运行此命令时,我的输出是“ None”。