【发布时间】:2021-06-08 02:37:47
【问题描述】:
我正在尝试将数据附加到字典中,同时从网页中抓取相同的数据。我此刻的输出不是我希望如何安排它们。这是webpage。
我试过了:
import requests
from bs4 import BeautifulSoup
from pprint import pprint
url = 'https://elllo.org/english/grammar/L1-01-AimeeTodd-Intros-BeVerb.htm'
data = []
r = requests.get(url)
soup = BeautifulSoup(r.text,"lxml")
for item in soup.select("#transcript p"):
d = {}
if "Aimee:" in item.text:
d['Aimee'] = item.text.replace("Aimee:","").strip()
elif "Todd:" in item.text:
d['Todd'] = item.text.replace("Todd:","").strip()
data.append(d)
pprint(data)
我得到的输出是:
[{'Aimee': 'So Todd, where are you from?'},
{'Todd': "I am from the U.S., I am from San Francisco. It's on the west "
'coast.'},
{'Aimee': 'And what do you do?'},
{'Todd': "I'm an English teacher. Also, I create Elllo. I work on Elllo a "
'lot.'}
预期输出:
[{'Aimee': 'So Todd, where are you from?','Todd': "I am from the U.S., I am from San Francisco. It's on the west "
'coast.'},
{'Aimee': 'And what do you do?','Todd': "I'm an English teacher. Also, I create Elllo. I work on Elllo a "
'lot.'},
我怎样才能产生第二个输出?
【问题讨论】:
-
您将如何决定对话何时结束?我将发布一个答案来说明如何获得这种效果,但这并不是一个真正强大的解决方案。
-
-
这可以让您存储对话,但它没有说明您如何知道对话何时结束。所有的对话都会有一个问题和一个回应吗?如果是这样,那么我怀疑我的答案是最佳的。
-
很抱歉未能理解您的问题。是的,对话是一个问题和一个响应的基础。
-
作为 Tim 的答案的替代方案,您可以将成绩单标签存储在列表
l中,并分两步迭代它 -for i in range(0, len(l) - 1, 2):。然后,您将在l[i]中看到 Aimee 的对话,在l[i+1]中看到 Tom 的对话。
标签: python json python-3.x dictionary web-scraping