3 回答
TA贡献1798条经验 获得超3个赞
您可以使用更快的类选择器来获取父级 ol ,然后使用 nth-of-type 来隔离特定行:
import requests
from bs4 import BeautifulSoup as bs
r = requests.get('https://www.serenataflowers.com/pollennation/love-text-messages/')
soup = bs(r.content, 'lxml')
line_number = 2
print(soup.select_one(f'.simple-list li:nth-of-type({line_number})').text)
如果在某个时候想要所有行但值得了解nth-of-type和相关技巧,则索引整个列表会更快。
TA贡献1856条经验 获得超11个赞
要获取每个引用中的文本列表,请使用您已经隔离findAll()的块上的方法。ol
ol = soup.find('ol')
messages = [msg.text for msg in ol.findAll('li')] # this goes through and isolates the text of each message
现在您可以通过它们的索引访问消息。请记住,列表的索引为 0,这意味着项目 1 实际上 = 0。
print(messages[0]) # Actually the first message
# output: Meeting you was the best day of my life.
添加回答
举报
