【问题标题】:How do I send an embed message that contains multiple links parsed from a website to a webhook?如何将包含从网站解析的多个链接的嵌入消息发送到 webhook?
【发布时间】:2020-02-11 13:38:56
【问题描述】:

我希望我的嵌入消息看起来像这样,但我的只返回一个链接。

这是我的代码:

import requests
from bs4 import BeautifulSoup
from discord_webhook import DiscordWebhook, DiscordEmbed

url = 'https://www.solebox.com/Footwear/Basketball/Lebron-X-JE-Icon-QS-variant.html'
headers = {'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.120 Safari/537.36'}
r = requests.get(url, headers=headers)
soup = BeautifulSoup(r.content, "lxml")
for tag in soup.find_all('a', class_="selectSize"):
    #There's multiple 'id' resulting in more than one link
    aid = tag.get('id')
    #There's also multiple sizes
    size = tag.get('data-size-us')
    #These are the links that need to be shown in the embed message
    product_links = "https://www.solebox.com/{0}".format(aid)

webhook = DiscordWebhook(url='WebhookURL')
embed = DiscordEmbed(title='Title')
embed.set_author(name='Brand')
embed.set_thumbnail(url="Image")
embed.set_footer(text='Footer')
embed.set_timestamp()
embed.add_embed_field(name='Sizes', value='US{0}'.format(size))
embed.add_embed_field(name='Links', value='[Links]({0})'.format(product_links))
webhook.add_embed(embed)
webhook.execute()

【问题讨论】:

  • type(product_links) 说它是List 还是String?乍一看,似乎for tag in soup.find_all('a', class_="selectSize") 的每次迭代都只是覆盖了product_links 的先前值

标签: python beautifulsoup discord webhooks discord.py


【解决方案1】:

这很可能会为您带来您想要的结果。 type(product_links) 是一个字符串,这意味着 for 循环中的每次迭代都只是用新字符串重写 product_links 变量。如果您在循环之前声明一个 List 并将 product_links 附加到该列表,它很可能会产生您想要的结果。

注意:我必须使用与该站点不同的 URL。问题中指定的那个不再可用。我还必须使用不同的标题,因为提问者不断给我一个 403 错误。

补充说明:通过您的代码逻辑返回的 URLS 会返回指向不通的链接。我觉得你需要解决这个问题,因为我不知道你到底想要做什么,但是我觉得这回答了为什么你只得到一个链接的问题。

import requests
from bs4 import BeautifulSoup

url = 'https://www.solebox.com/Footwear/Basketball/Air-Force-1-07-PRM-variant-2.html'

headers = {"User-Agent": "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.3"}

r = requests.get(url=url, headers=headers) 

soup = BeautifulSoup(r.content, "lxml")

product_links = [] # Create our product

for tag in soup.find_all('a', class_="selectSize"):
    #There's multiple 'id' resulting in more than one link
    aid = tag.get('id')
    #There's also multiple sizes
    size = tag.get('data-size-us')
    #These are the links that need to be shown in the embed message
    product_links.append("https://www.solebox.com/{0}".format(aid))

【讨论】:

    猜你喜欢
    • 2020-10-19
    • 2021-02-12
    • 1970-01-01
    • 2017-10-16
    • 1970-01-01
    • 2021-01-29
    • 1970-01-01
    • 2019-07-05
    • 1970-01-01
    相关资源
    最近更新 更多