import collections.OrderedDict
import requests
from bs4 import BeautifulSoup
r = requests.get('https://www.youtube.com/playlist?list=PLIeGtxpvyG-JI5RDHtjk0NtyQPirBfBpu')
r.status_code
if r.status_code == 200 :
soup = BeautifulSoup (r.text,'html.parser')
OrderedDict.dict = {}
for i in soup.findAll('td',{'class':'pl-video-title'}):
#print i
dict [i.find('a').text] = i.findAll('td' , { 'class': "pl-video-time"})[0].text
for i,k in collections.OrderedDict.dict.items():
print i, k
我能够成功运行该程序,但我希望保留相同的顺序。我想知道如何在我的案例中使用'OrderedDict'模块。如果我使用'OrderedDict'模块我会收到错误。
答案 0 :(得分:1)
from collections import OrderedDict
import requests
from bs4 import BeautifulSoup
r = requests.get('https://www.youtube.com/playlist?list=PLIeGtxpvyG-JI5RDHtjk0NtyQPirBfBpu')
if r.status_code == 200:
soup = BeautifulSoup(r.text, 'html.parser')
d = OrderedDict()
for i in soup.findAll('td', {'class': 'pl-video-title'}):
d[i.find('a').text] = i.findAll('td', {'class': "pl-video-time"})[0].text
for i, k in d.items():
print i, k
首先,您必须从集合模块导入OrderedDict。
我删除了悬空r.status_code,因为它没有做任何事情,然后将所有内容放在if r.status_code == 200中,否则你得到一个NameError异常,我也把dict更改为d ,因为你要遮蔽那个变量,除此之外我还修改了格式。
答案 1 :(得分:0)
实例化你必须要做的OrderedDict
myOrderedDict = OrderedDict([])
不
OrderedDict.dict = {}
并遍历有序的dict,它将是
for i,j in in myOrderedDict.items():
#do something with i and j