我正在尝试查找并存储 children <orgname>
来自家长 <assignee>
。到目前为止,我的代码运行在已经拾取某些其他标签的 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>
下的组织名称标签。我试过:
分配 = soup.findAll("受让人") org_name = allocate.findAll("组织名称")
但是没有效果。它只是简单地射出:
"ResultSet object has no attribute '%s'. You're probably treating a list of items like a single item. Did you call find_all() when you meant to call find()?" % key
AttributeError: ResultSet object has no attribute 'find'. You're probably treating a list of items like a single item. Did you call find_all() when you meant to call find()?
如何添加这些标签并查找受让人标签下的所有组织名称? 看起来很简单,但我看不懂。
提前致谢。
最佳答案
assign = soup.findAll("assignee")
返回一个 list ,这就是调用 org_name = assign.findAll("orgname")
的原因失败,您必须遍历 assign
的每个元素并将其称为 .findAll("orgname")
,但似乎只有一个<orgname>
在每个 <assignee>
,所以不需要使用.findAll
而不是.find
。尝试使用.find
到 assign
的每个元素使用列表理解:
orgnames = [item.find("orgname") for item in assign]
或者,要直接获取他们的文本,请先检查 <orgname>
是否存在存在于其中 <assignee>
:
orgnames = [item.find("orgname").text for item in assign if item.find("orgname")]
关于python - 在 Beautiful Soup 中查找并存储根的子代,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45724784/