使用BS4从多个标记中提取数据后如何分割信息

2024-10-02 04:25:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我是Python新手。从文档中提取列表时出现问题。我的源文件不是真正的html,但它有一个标签来提取所需的数据

enter image description here

我使用此代码设法提取所需的数据

from bs4 import BeautifulSoup
url = r"E:\Python\Sources\test.review"
page = open(url)
soup = BeautifulSoup(page.read())
for review in soup.find_all(['review_text','product_name']):
    tokens=review.get_text()
    print tokens

然而,由于我不太熟悉在Python中使用list,因此存在如何破坏结果的问题。我尝试使用此代码,但它只返回第一个数据。我相信它,因为它引用了文件中的第一个数据。谢谢你的反馈

rvwTxt=soup.review_text.string
pName=soup.product_name.string
print rvwTxt
print pName

Tags: 数据代码textnameurlstringpageproduct
1条回答
网友
1楼 · 发布于 2024-10-02 04:25:37

您可以在dict中分组,使用标记名进行分组,这样您就可以在一次过程中完成分组:

soup = BeautifulSoup(page.read(),"xml")
d = {"review_text":[], "product_name": []}
for review in soup.find_all(['review_text','product_name']):
    d[review.name].append(review.get_text())

或使用两个列表组件:

rev = [r.text for r in soup.find_all('product_name')]
prod = [p.text for p in soup.find_all('review_text')]

相关问题 更多 >

    热门问题