Python I';我正在抓取沃尔玛,但每当我输入一个带有搜索URL的函数参数来抓取时,当我试图打印它时,我只会得到一个参数

Python I';我正在抓取沃尔玛,但每当我输入一个带有搜索URL的函数参数来抓取时,当我试图打印它时,我只会得到一个参数,python,python-3.x,function,web-scraping,Python,Python 3.x,Function,Web Scraping,当代码不是函数且LegoWebsite=URL时,刮取工作正常。唯一的问题是我希望它更加动态,这样我就可以在沃尔玛上输入任何搜索URL,它就会显示价格。我面临的问题是,当我运行此命令时,我的输出为“无”。变量文本永远不会被创建,因为它是循环外的 import ssl from urllib.request import urlopen as uReq from bs4 import BeautifulSoup as soup context = ssl._create_unverified_

当代码不是函数且LegoWebsite=URL时,刮取工作正常。唯一的问题是我希望它更加动态,这样我就可以在沃尔玛上输入任何搜索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)
当你打印出你的价目表是空的,因为没有附加任何东西 秘书长:

if语句不存在never gets True cos文本变量

试试这个:

if text[0] == "$":

由于您的“PriceOfLegos”返回,您打印的“z”和“z”已分配给NoneNone@MariosKeri但是我在我函数的末尾写着“对于价格中的x:print($”,x,sep=“”)”``那么z不应该返回我函数的末尾,也就是说打印出所有价格中的x吗?嘿,这很有效,谢谢。我所做的最后一件事是将它从函数“z:print($”,x,sep=”“)中去掉```
if text[0] == "$":
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")