使用python汤提取动态HTML标记之间的文本
问题描述:
我有一个需求,我需要提取HTML标记之间的文本。我使用BeautifulSoup提取数据并将文本存储到变量中以供进一步处理。后来我发现,我需要提取的文本来自两个不同的标签。但请注意,我需要提取文本并存储到相同的变量中。我提供了我早期的代码和示例HTML文本信息。请帮助我如何获得最终结果,即预期产出。使用python汤提取动态HTML标记之间的文本
示例HTML文本:
<DIV CLASS="c0"><P CLASS="c1"><SPAN CLASS="c2">1 of 80 DOCUMENTS</SPAN></P>
<DIV CLASS="c0"><BR><P CLASS="c1"><SPAN CLASS="c2">Financial Times (London, England)</SPAN></P>
<DIV CLASS="c0"><BR><P CLASS="c1"><SPAN CLASS="c2">Copyright 2015 The Financial Times Ltd.<BR>All Rights Reserved<BR>Please do not cut and paste FT articles and redistribute by email or post to the web.</SPAN></P>
<DIV CLASS="c0"><P CLASS="c1"><SPAN CLASS="c2">80 of 80 DOCUMENTS</SPAN></P>
</DIV>
<BR><DIV CLASS="c3"><P CLASS="c1"><SPAN CLASS="c2">Financial Times (London,England)</SPAN></P>
</DIV>
<DIV CLASS="c3"><P CLASS="c1"><SPAN CLASS="c2">Copyright 1990 The Financial Times Limited</SPAN></P>
</DIV>
从上面的HTML文本,我需要(80 1的文件,80 80的文档)文档存储到一个单一的变量。类似的其他文字也遵循类似的方法。我写了div.c0的代码
soup = BeautifulSoup(response, 'html.parser')
docpublicationcpyright = soup.select('div.c0')
list1 = [b.text.strip() for b in docpublicationcpyright]
doccountvalues = list1[0:len(list1):3]
publicationvalues = list1[1:len(list1):3]
copyrightvalues = list1[2:len(list1):3]
documentcount = doccountvalues
publicationpaper = publicationvalues
任何帮助将不胜感激。
答
鉴于示例HTML结构不正确。例如:第一个DIV元素缺少结束标记。反正这种类型的HTML也使用正则表达式您可以刮取所需的数据。
我写了一个示例代码考虑张贴在这个问题&能够提取所有三个必填字段
soup = BeautifulSoup(response, 'html.parser')
documentElements = soup.find_all('span', text=re.compile(r'of [0-9]+ DOCUMENTS'))
documentCountList = []
publicationPaperList = []
documentPublicationCopyrightList = []
for elem in documentElements:
documentCountList.append(elem.get_text().strip())
if elem.parent.find_next_sibling('div'):
publicationPaperList.append(elem.parent.find_next_sibling('div').find('span').get_text().strip())
documentPublicationCopyrightList.append(elem.parent.find_next_sibling('div').find_all('span')[1].get_text())
else:
publicationPaperList.append(elem.parent.parent.find_next('div').get_text().strip())
documentPublicationCopyrightList.append(elem.parent.parent.find_next('div').find_next('div').get_text().strip())
print(documentCountList)
print(publicationPaperList)
print(documentPublicationCopyrightList)
输出看起来像只样本HTML下面
[u'1 of 80 DOCUMENTS', u'80 of 80 DOCUMENTS']
[u'Financial Times (London, England)', u'Financial Times (London,England)']
[u'Copyright 2015 The Financial Times Ltd.All Rights ReservedPlease do not cut and paste FT articles and redistribute by email or post to the web.', u'Copyright 1990 The Financial Times Limited']
+0
谢谢。它运行良好。 – Mho
谁能帮我出这个 – Mho
发布您想要的输出样本。 –
样本输出:documentcount = [80个文档中的80个,80个文档中的80个],publicationpaper = [Financial Times(London,England),Financial Times(London,England)] – Mho