【发布时间】:2019-11-28 17:14:06
【问题描述】:
我正在尝试为维基百科页面提取一些信息,并且我正在使用 Beautiful soup 将文本加载到 Python 中,但我似乎无法使用正则表达式去除所有不必要的标签。
这是来自美丽汤的文本输出示例
[<td colspan="3">
</td>, <td valign="top" width="400">
<ul><li><a href="/wiki/Aach,_Baden-W%C3%BCrttemberg" title="Aach, Baden-Württemberg">Aach</a> (<a href="/wiki/Baden-W%C3%BCrttemberg" title="Baden-Württemberg">Baden-Württemberg</a>)</li>
<li><a href="/wiki/Aachen" title="Aachen">Aachen</a> (<a href="/wiki/North_Rhine-Westphalia" title="North Rhine-Westphalia">North Rhine-Westphalia</a>)</li>
理想情况下,我希望拥有城市(分配给标题)和区域(就在行尾之前)。
任何帮助将不胜感激!
rows = soup.find_all('td')
list_rows = []
#remove html tags
for row in rows:
cells = row.find_all('li')
str_cells = str(cells)
clean = re.compile('<.*?>')
clean2 = (re.sub(clean, '', str_cells))
list_rows.append(clean2)
print(clean2)
【问题讨论】:
-
可以分享一下维基百科页面的网址吗?
-
结束锚标记 (
</a>) 之前的文本也是区域吗? -
在某些情况下是的,其中区域是超链接,但在其他情况下,区域就在结束锚标记之前 ()
标签: python regex python-3.x beautifulsoup