将输出传输到lis

2024-06-26 01:36:52 发布

您现在位置:Python中文网/ 问答频道 /正文

如何传输以下代码的输出:

“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.”

一个列表式的版本?你知道吗

[[“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.”]]

这是我的密码:

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

Tags: thetextinfromimportisaspage
1条回答
网友
1楼 · 发布于 2024-06-26 01:36:52
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.”']]

相关问题 更多 >