首页 > 解决方案 > 在 Beutifulsoup4 中查找多个标签并将它们插入到一个字符串中

问题描述

有一个代码可以获取您的 pastebin 数据


def user_key():
    user_key_data = {'api_dev_key': 'my-dev-key',
                     'api_user_name': 'my-username',
                     'api_user_password': 'my-password'}
    req = urllib.request.urlopen('https://pastebin.com/api/api_login.php',
                                 urllib.parse.urlencode(user_key_data).encode('utf-8'),
                                 timeout=7)
    return req.read().decode()


def user_pastes()
    data = data = {'api_dev_key': 'my_dev_key',
                   'api_user_key': user_key(),
                   'api_option': 'list'}
    req = urllib.request.urlopen('https://pastebin.com/api/api_post.php',
                                 urllib.parse.urlencode(data).encode('utf-8'), timeout=7)
    return req.read().decode()

每个粘贴都有一个唯一的 html 标记,例如 url、标题、粘贴键等。上面的代码将在每次粘贴时打印出来。我制作了一个只需要某些标签的代码。粘贴网址、粘贴标题和粘贴键

    my_pastes = []
    src = user_pastes()
    soup = BeautifulSoup(src, 'html.parser')
    for paste in soup.findAll(['paste_url', 'paste_title', 'paste_key']):
        my_pastes.append(paste.text)
    print(my_pastes)

我想要的是将每次粘贴的 url、标题和键连接到一个字符串中。我尝试使用 .join 方法,但它只加入字符。(可能没有意义,但你会在尝试时看到)

与问题无关。他们加入后我会做什么。再次拆分它们并将它们放入 PyQt5 表中 在此处输入图像描述

标签: pythonpython-3.xbeautifulsouppastebin

解决方案


所以这是一种答案,但我仍在寻找更简单的代码

    title = []
    key = []
    url = []
    src = user_pastes()
    soup = BeautifulSoup(src, 'html.parser')
    for paste_title in soup.findAll('paste_title'):
        title.append(paste_title.text)
    for paste_key in soup.findAll('paste_key'):
        key.append(paste_key.text)
    for paste_url in soup.findAll('paste_url'):
        url.append(paste_url.text)
    for i in range(len(title)):
        print(title[i], key[i], url[i])

也许从这个答案中你会明白我想要实现的目标,因为这篇文章有点令人困惑,因为我无法真正表达我想要什么


推荐阅读