python - 在 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 方法,但它只加入字符。(可能没有意义,但你会在尝试时看到)
解决方案
所以这是一种答案,但我仍在寻找更简单的代码
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])
也许从这个答案中你会明白我想要实现的目标,因为这篇文章有点令人困惑,因为我无法真正表达我想要什么
推荐阅读
- jquery - 为什么使用多个表单输入的 Dropzone 图像上传不起作用
- c# - 将数据传递到 excel - 通过 ASP.NET Web 应用程序的多个工作表
- swift - 理解 SwiftUI 中的 @Binding
- javascript - 尝试对数字输入求和时出现 NaN 错误
- c - 释放导致崩溃
- javascript - jQuery如何从焦点输入字段值中删除
- ios - tableView 单元格未显示单元格中的任何内容,但它正在控制台中打印内容
- ansible - ansible角色造成的模板错误如何解决
- excel - 如果活动单元格包含特定文本,则清除其内容
- heroku - 由于依赖私有仓库,无法在 Heroku 上部署 Elixir 应用程序