【问题标题】:Assigning variables to scraped values将变量分配给抓取的值
【发布时间】:2021-06-01 16:33:55
【问题描述】:

使用beautifulsoup 抓取一个网站(这里以这个人为例:https://rocket-league.com/player/Guuter),我已经设法得到了我想要的文本。但是,我不知道如何正确地将每个字符串分配给某些变量,以便正确格式化它们。这是一个交易网站,所以我想将交易分为“有”和“想要”部分

到目前为止我所取得的成就(顺便说一句,包括巨大的差距):

Has:



#first item
Titanium White #colour

Credits #item


200 #amount




#second item
Titanium White #colour

Credits #item


250 #amount

Wants:




Titanium White #colour

Neo-Thermal #item

#no amount this time - therefore is 1





#second item
Grey #colour

Halo #item

#once again no amount - therefore is 1

这是一个不和谐的机器人,当你用命令查找某人的名字时,它会给你他们的第一笔交易(想要更多 - 请让我知道如何做到这一点 - 不让我使用 find_all 没有错误)

@bot.command()
async def rlgarage(ctx, arg):
 name = arg
 #name = "Guuter"
 page = requests.get("https://rocket-league.com/player/"+name)
 soup = BeautifulSoup(page.content, 'html.parser')

 tradeitems = soup.find(class_="rlg-trade__items")
 haveitems = tradeitems.find(class_="rlg-trade__itemshas")
 haveitemstext = haveitems.get_text()
 wantitems = tradeitems.find(class_="rlg-trade__itemswants")
 wantitemstext = wantitems.get_text()
 await ctx.send("Has:" + haveitemstext + "Wants:" + wantitemstext)

首选输出:

Has:

Titanium White Credits (200)

Titanium White Credits (250)

Wants:

Titanium White Neo-Thermal

Grey Halo

【问题讨论】:

    标签: python beautifulsoup


    【解决方案1】:

    我已经从a 标记中获取项目并附加到lst 并通过分成两部分来使用连接操作,您可以使用此代码,但如果网页上的总项目只有 2,您可以设置条件来处理它

    import requests
    from bs4 import BeautifulSoup
    page = requests.get("https://rocket-league.com/player/Guuter")
    soup = BeautifulSoup(page.content, 'html.parser')
    
    tradeitems = soup.find("div",class_="rlg-trade__items")
    lst=[]
    for i in tradeitems.find_all("a"):
        lst.append(i.get_text(strip=True,separator=" "))
    print("Has :\n"+"\n".join(lst[:2])+"\nWants :\n"+"\n".join(lst[2:]))
    

    输出:

    Has :
    Titanium White Credits 200
    Titanium White Credits 250
    Wants :
    Titanium White Neo-Thermal
    Grey Halo
    

    【讨论】:

    • ty 完美运行 - 请注意 1. 它如何与 a 标签一起使用? - 2. 我怎样才能对多笔交易重复这个 - 所以它列出了多个
    • 您已经完成了一个,现在您可以在 tradeitmes 中使用find_all 完成多个
    • 我应该找到哪一个?
    • 看到我提到我们已经采用了一个tradeitem 现在使用find_all 方法并再次迭代找到a tag 并将数据附加到列表并使用该数据试试吧!
    • sry 但是当使用tradeitems = soup.find_all("div",... 我得到AttributeError: ResultSet object has no attribute 'find_all'. You're probably treating a list of elements like a single element. Did you call find_all() when you meant to call find()?
    猜你喜欢
    • 2013-03-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-04
    • 1970-01-01
    • 1970-01-01
    • 2019-05-01
    相关资源
    最近更新 更多