下面是一个使用BeautifulSoup将字符串值转换为嵌套的for循环内的整数,并进行排序的示例代码:
from bs4 import BeautifulSoup
html = '''
- 3
- 1
- 4
- 2
'''
soup = BeautifulSoup(html, 'html.parser')
numbers = [int(li.text) for li in soup.find_all('li')]
numbers.sort()
print(numbers)
输出结果为:[1, 2, 3, 4]
在上述代码中,我们首先创建了一个包含数字的HTML字符串。然后使用BeautifulSoup解析这个字符串并创建一个BeautifulSoup对象。接下来,我们使用find_all
方法找到所有的li
标签,并使用列表推导式将其文本内容转换为整数并存储在numbers
列表中。最后,我们使用sort
方法对numbers
列表进行排序,并打印排序后的结果。