Python 3.x 如何从列表中提取一些特定字符串并将它们存储在beautifulsoup的变量中?
我想在包含多个标记(和字符串)的多个项目列表中提取特定字符串。并将它们存储到变量中Python 3.x 如何从列表中提取一些特定字符串并将它们存储在beautifulsoup的变量中?,python-3.x,web-scraping,beautifulsoup,html-parsing,Python 3.x,Web Scraping,Beautifulsoup,Html Parsing,我想在包含多个标记(和字符串)的多个项目列表中提取特定字符串。并将它们存储到变量中 from bs4 import BeautifulSoup from requests_html import HTMLSession session = HTMLSession() r = session.get('https://www.khanacademy.org/profile/DFletcher1990/') r.html.render(sleep=5) soup=BeautifulSoup(r.h
from bs4 import BeautifulSoup
from requests_html import HTMLSession
session = HTMLSession()
r = session.get('https://www.khanacademy.org/profile/DFletcher1990/')
r.html.render(sleep=5)
soup=BeautifulSoup(r.html.html,'html.parser')
user_socio_table=soup.find_all('div', class_='discussion-stat')
print(user_socio_table)
以下是打印(用户表)
的假定输出:
[
4个问题
,
444票
,
718个答案
,
升起15面旗帜
,
10个项目帮助请求
,
38项目帮助答复
,
208评论
,
11点提示和感谢
]
- 我想将
存储到名为4
的变量中questions
- 我想将
存储到名为444
的变量中voces
- 我想将
存储到名为718
的变量中answers
- 我想将
存储到名为15
的变量中flags
- 我想将
存储到名为10
的变量中help\u requests
- 我想将
存储到名为38
的变量中help\u repress
- 我想将
存储到名为208
的变量中comments
- 我想将
存储到名为11
tips\u谢谢
的变量中
谢谢你的帮助 您可以逐个获取值并将其添加到json数组中
data = {}
for gettext in user_socio_table:
category = gettext.find('span')
category_text = category.text.strip() ## get text in span
number = category.previousSibling.strip() ## get value before span tag
data[category_text] = number ## add it
print(data)
输出:
{'questions': '4', 'votes': '444', 'answers': '718', 'flags raised': '15', 'project help requests': '10', 'project help replies': '38', 'comments': '208', 'tips and thanks': '11'}
4
您可以使用spesific one获得价值
print(data['questions'])
输出:
{'questions': '4', 'votes': '444', 'answers': '718', 'flags raised': '15', 'project help requests': '10', 'project help replies': '38', 'comments': '208', 'tips and thanks': '11'}
4