python - 在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>
解决方案
你可以简单地尝试在正则表达式中捕获这个标签,这样的事情会起作用
>>>import re
>>> temp = """<h3>
... dog1
... </h3>
...
... <h3>
... dog2
... </h3>"""
>>> temp = temp.replace("\n", "")
>>> re.findall(r'<h3>(.*?)</h3>', temp, re.MULTILINE)
['dog1', 'dog2']
>>>
推荐阅读
- angular5 - 角度 5,使用 (ngModelChange) 更改模型时未采用新模型值
- static - SystemVerilog:自动变量不能为静态 reg 出现非阻塞赋值
- python - 在 Pandas 上过滤列表元素
- sapui5 - Ui5 中的日期选择器允许输入整数
- javascript - Javascript 运算符优先级(关联性)
- python - 将 py 文件转换为 exe,找不到现有的 PyQt5 插件目录
- ios - Objective C 中的@dynamic 属性
- java - 无法使用 Selenium Java 访问某些 URL
- javascript - 如何使儿童订单随机化器具有重置回初始订单的选项?
- reactjs - Axios 请求超时