我正在抓捕沃尔玛,但是每当我输入带有要刮除搜索URL的函数的参数时,我在尝试打印时都一无所获

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”。

xu414816349 回答:我正在抓捕沃尔玛,但是每当我输入带有要刮除搜索URL的函数的参数时,我在尝试打印时都一无所获

可变文本永远不会被创建,因为cos不在循环中

if text[0] == "$":
    price.append(text[1:])

,并且在打印输出时,价目表为空,因为未附加任何内容 cos:

if text[0] == "$":

对于if语句,永远不会获得True cos文本变量的剂量

尝试一下:

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="")


PriceOfLegos("https://www.walmart.com/search/?query=Lego%20horse")
本文链接:https://www.f2er.com/3115324.html

大家都在问