如何遍历 soup.findAll('tag1', 'tag2', 'tag3') 中的多个标签?
How can I iterate over multiple tags in soup.findAll('tag1', 'tag2', 'tag3')?
我正在尝试编写一个 python 脚本,可以自动修改多个 html 文件中的某些标签; 运行 来自终端的单个命令。
我构建了代码库。
在我的代码库中,我做了如下所示的事情。有没有更方便的方法用更少的代码来做到这一点?
#modifying the 'src' of <img> tag in the soup obj
for img in soup.findAll('img'):
img['src'] = '{% static ' + "'" + img['src'] + "'" + ' %}'
#modifying the 'href' of <link> tag in the soup obj
for link in soup.findAll('link'):
link['href'] = '{% static ' + "'" + link['href'] + "'" + ' %}'
#modifying the 'src' of <script> tag in the soup obj
for script in soup.findAll('script'):
script['src'] = '{% static ' + "'" + script['src'] + "'" + ' %}'
例如,我可以用单个 for 循环而不是 3 个来完成吗?并不是说它必须像我在下面写的那样,任何好的实践建议都是我正在寻找的。
for img, link, script in soup.findAll('img', 'link', 'script'):
rest of the code goes here....
也许使用字典来检索适当的属性?此外,使用更快的 css 选择器。
import requests
from bs4 import BeautifulSoup as bs
r = requests.get('
soup = bs(r.content, 'lxml')
lookup = {
'img':'src',
'link': 'href',
'script':'src'
}
for i in soup.select('img, link, script'):
var = lookup[i.name]
if i.has_attr(var):
i[var] = '{% static ' + "'" + i[var] + "'" + ' %}'
print(i[var])
是的,你可以。
您可以将元素列表传递给 findAll 方法
for element in soup.findAll(['img', 'link', 'script']): # use find_all for bs4
if element.name == 'img':
value = element['src']
elif element.name == 'href':
value = element['href']
elif element.name == 'script':
value = element['src']
else:
continue
print(val)
我正在尝试编写一个 python 脚本,可以自动修改多个 html 文件中的某些标签; 运行 来自终端的单个命令。
我构建了代码库。
在我的代码库中,我做了如下所示的事情。有没有更方便的方法用更少的代码来做到这一点?
#modifying the 'src' of <img> tag in the soup obj
for img in soup.findAll('img'):
img['src'] = '{% static ' + "'" + img['src'] + "'" + ' %}'
#modifying the 'href' of <link> tag in the soup obj
for link in soup.findAll('link'):
link['href'] = '{% static ' + "'" + link['href'] + "'" + ' %}'
#modifying the 'src' of <script> tag in the soup obj
for script in soup.findAll('script'):
script['src'] = '{% static ' + "'" + script['src'] + "'" + ' %}'
例如,我可以用单个 for 循环而不是 3 个来完成吗?并不是说它必须像我在下面写的那样,任何好的实践建议都是我正在寻找的。
for img, link, script in soup.findAll('img', 'link', 'script'):
rest of the code goes here....
也许使用字典来检索适当的属性?此外,使用更快的 css 选择器。
import requests
from bs4 import BeautifulSoup as bs
r = requests.get('
soup = bs(r.content, 'lxml')
lookup = {
'img':'src',
'link': 'href',
'script':'src'
}
for i in soup.select('img, link, script'):
var = lookup[i.name]
if i.has_attr(var):
i[var] = '{% static ' + "'" + i[var] + "'" + ' %}'
print(i[var])
是的,你可以。 您可以将元素列表传递给 findAll 方法
for element in soup.findAll(['img', 'link', 'script']): # use find_all for bs4
if element.name == 'img':
value = element['src']
elif element.name == 'href':
value = element['href']
elif element.name == 'script':
value = element['src']
else:
continue
print(val)