首页 > 解决方案 > 无法以正确的顺序排列 Web 解析的结果

问题描述

我试图使用BeautifulSoupdrequests库从维基百科获取颜色列表。我得到了结果,但无论我多么努力都无法以正确的顺序得到结果,以便我可以写入一个文件,该文件又将用于另一个程序。所以,请帮忙。下面是代码。

# coding: utf-8
from bs4 import BeautifulSoup
import requests
r = requests.get('https://en.wikipedia.org/wiki/List_of_colors_(compact)')
soup = BeautifulSoup(r.text, 'html.parser')
for i in soup.find_all('p'):
    print (i.text, i.get('title'))

上述代码的结果(示例):

  (79° 42% 89%)
 (197 227 132)
 #C5E384
Yellow-green (Crayola) None

  (36° 62% 89%)
 (227 171 87)
 #E3AB57
Sunray None

  (30° 25% 100%)
 (255 223 191)
 #FFDFBF
Very pale orange None

期望的结果(仅包括 RGB 值和以空格分隔的行中的名称):

197 227 132 Yellow-green (Crayola)
227 171 87 Sunray
255 223 191 Very pale orange

标签: pythonbeautifulsoup

解决方案


您可以组合两个列表,因为它们的长度匹配。我使用 css 选择器来隔离两个列表(一个用于颜色 soup.select('p[style="width:9em;padding:5px;margin:auto;"]') ,一个用于 rgbs soup.select('p[title]'))。我提取列表title中每个元素的属性,rgbs然后正则表达式输出所需的字符串。我只是将.text用于列表中a返回的子标签colours

import requests
from bs4 import BeautifulSoup as bs
import re

r = requests.get('https://en.wikipedia.org/wiki/List_of_colors_(compact)')
soup = bs(r.content, 'lxml')
p = re.compile(r' \((.*)\)')
for rgb, colour in zip(soup.select('p[title]'), soup.select('p[style="width:9em;padding:5px;margin:auto;"]')):
    print(p.findall(rgb['title'])[0], colour.text)

输出样本:

在此处输入图像描述


推荐阅读