在美丽的汤中寻找和储存根的孩子



我正在尝试查找并存储父<assignee><orgname>子项。到目前为止,我的代码通过XML文档运行,已经拾取了某些其他标签 - 我已经这样设置了它:

for xml_string in separated_xml(infile): # Calls the output of the separated and read file to parse the data
soup = BeautifulSoup(xml_string, "lxml")     # BeautifulSoup parses the data strings where the XML is converted to Unicode
pub_ref = soup.findAll("publication-reference") # Beginning parsing at every instance of a publication
lst = []  # Creating empty list to append into
with open('./output.csv', 'ab') as f:
writer = csv.writer(f, dialect = 'excel')
for info in pub_ref:  # Looping over all instances of publication
# The final loop finds every instance of invention name, patent number, date, and country to print and append
for inv_name, pat_num, date_num, country, city, state in zip(soup.findAll("invention-title"), soup.findAll("doc-number"), assign.find("orgname"), soup.findAll("date"), soup.findAll("country"), soup.findAll("city"), soup.findAll("state")):
writer.writerow([inv_name.text, pat_num.text, org_name.text, date_num.text, country.text, city.text, state.text])

我已经按顺序排列了这个,以便每个发明名称和专利对,并且需要组织受让人名称以及它。问题是还有其他标签与律师和此类组织相关联,如下所示:

<agent sequence="01" rep-type="attorney">
<addressbook>
<orgname>Sawyer Law Group LLP</orgname>
<address>
<country>unknown</country>
</address>
</addressbook>
</agent>
</agents>
</parties>
<assignees>
<assignee>
<addressbook>
<orgname>International Business Machines Corporation</orgname>
<role>02</role>
<address>
<city>Armonk</city>
<state>NY</state>
<country>US</country>
</address>
</addressbook>
</assignee>
</assignees>

我只想要<assignee>标签下的组织名称。我试过:

assign = soup.findAll("assignee"( org_name = assign.findAll("orgname"(

但无济于事。它只是射出:

"结果集对象没有属性 '%s'。您可能正在治疗 项目列表,如单个项目。当你调用find_all(( 打算调用 find((?">

属性错误:结果集对象没有属性"find"。你是 可能将项目列表视为单个项目。你打过电话吗 find_all(( 当你打算调用 find(( 时?

如何添加这些标签并在受让人标签下找到所有组织名称? 这看起来很简单,但我无法理解。

提前谢谢。

assign = soup.findAll("assignee")返回一个列表,所以这就是为什么调用org_name = assign.findAll("orgname")失败的原因,你必须遍历assign的每个元素并调用它.findAll("orgname"),但似乎每个<assignee>只有一个<orgname>,所以没有必要使用.findAll代替.find。尝试使用列表推导对assign的每个元素使用.find

orgnames = [item.find("orgname") for item in assign]

或者,要直接获取他们的文本,请在该<assignee>中检查<orgname>是否存在:

orgnames = [item.find("orgname").text for item in assign if item.find("orgname")]

最新更新