【问题标题】:how to divide information after extracting data from multiple tags using BS4使用BS4从多个标签中提取数据后如何划分信息
【发布时间】:2016-06-21 09:26:38
【问题描述】:

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

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

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 中使用列表。我尝试使用此代码,但它只返回第一个数据。我相信它,因为它引用了文件中的第一个数据。感谢您的所有反馈。

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

【问题讨论】:

  • edit您的问题并将XML作为代码包含在内。

标签: python beautifulsoup


【解决方案1】:

您可以在字典中分组,使用标签名称进行分组,这样您就可以一次完成:

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')]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-24
    • 1970-01-01
    • 2013-12-26
    • 2016-07-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多