首页 > 解决方案 > 在python中修改列表项

问题描述

我有一个 html 文件(通过 curl 拉取;以避免用我的试验来 ping 网站),其中包含狗列表,并且我对 h3 标记内容感兴趣,这是狗的名字。

from urllib.request import urlopen
from bs4 import BeautifulSoup

# read from previously saved file
url  = "petrescue_short.html"
page = open(url)
soup = BeautifulSoup(page.read(), "html.parser")

# print all h3 tags; find_all returns a list! (not array)
h3_headers = soup.find_all(['h3'])
print('List all h3 header tags :', *h3_headers, sep='\n\n')

这将提供以下结果:

<h3>
dog1
</h3>

<h3>
dog2
</h3>

...

但是,我想摆脱标签或至少是换行符,并尝试了各种以错误消息告终的事情TypeError: 'NoneType' object is not callable。我还读到了:如何在 for 循环期间修改列表条目?但那里显示的列表实际上是一个数组。

我有点理解列表不是数组,但是没有办法遍历列表(我可以这样做)并且如果我不能更改列表项,至少将它分配给另一个变量并修改它?

我原以为以下应该有效:

for i in range(len(h3_headers)):
    h3_item = h3_headers[i]
    h3_item = h3_item.replace('\n', '')
    print(h3_item, sep='\n')

我怎样才能实现以下目标:

<h3>dog1</h3>
<h3>dog2</h3>
<h3>...</h3>

标签: pythonpython-3.xlist

解决方案


你可以简单地尝试在正则表达式中捕获这个标签,这样的事情会起作用

>>>import re
>>> temp = """<h3>
... dog1
... </h3>
... 
... <h3>
... dog2
... </h3>"""
>>> temp = temp.replace("\n", "")
>>> re.findall(r'<h3>(.*?)</h3>', temp, re.MULTILINE)
['dog1', 'dog2']
>>> 

推荐阅读