如何从以下代码传输输出:
“哈里,正是我们的选择表明了我们真正的身份,远远超过了我们的能力。”
“只有两种生活方式。一个好像没有什么是奇迹。另一个好像一切都是奇迹。”
“对于一本好小说不高兴的人,无论是绅士还是女士,都必须是无法容忍的愚蠢。”
到类似版本的列表?
[[“是我们的选择,哈里,表明我们真正是什么,远远超过我们的能力。”],
[“只有两种生活方式可以生活。一个好像没有什么是奇迹。另一个好像一切都是奇迹。”],
[“对一本好小说不满意的人,无论是绅士还是女士,都必须是无法容忍的愚蠢。”]
这是我的代码:
from random import choice,sample
import requests
from bs4 import BeautifulSoup
from csv import writer
page = 1
response = requests.get('http://quotes.toscrape.com/page/'+ str(page))
soup = BeautifulSoup(response.text, 'html.parser')
articles = soup.find_all(class_="quote")
for a in articles:
list_of_quotes = []
data = a.find(class_="text")
quotes = data.get_text()
list_of_quotes.append(quotes)
data1 = a.find(class_="author")
author = data1.get_text()
data3 = a.find('a')
href = data3['href']
print(quotes)`from random import choice,sample
答案 0 :(得分:2)
articles = soup.find_all(class_="quote")
for a in articles:
list_of_quotes = [] # < shouldn't be inside of a loop
data = a.find(class_="text")
quotes = data.get_text()
list_of_quotes.append(quotes)
list_of_quotes = []
for a in articles:
data = a.find(class_="text")
quotes = data.get_text()
list_of_quotes.append(quotes)
# or in one line
list_of_quotes = [a.find(class_="text").get_text() for a in articles]
# if you need output as a nested list
nested_list = [[x] for x in list_of_quotes]
# nested_list
[['“The world as we have created it is a process of our thinking. It cannot be changed without changing our thinking.”'],
['“It is our choices, Harry, that show what we truly are, far more than our abilities.”'],
['“There are only two ways to live your life. One is as though nothing is a miracle. The other is as though everything is a miracle.”'],
['“The person, be it gentleman or lady, who has not pleasure in a good novel, must be intolerably stupid.”'],
["“Imperfection is beauty, madness is genius and it's better to be absolutely ridiculous than absolutely boring.”"],
['“Try not to become a man of success. Rather become a man of value.”'],
['“It is better to be hated for what you are than to be loved for what you are not.”'],
["“I have not failed. I've just found 10,000 ways that won't work.”"],
["“A woman is like a tea bag; you never know how strong it is until it's in hot water.”"],
['“A day without sunshine is like, you know, night.”']]