python - 无法以正确的顺序排列 Web 解析的结果
问题描述
我试图使用BeautifulSoup
drequests
库从维基百科获取颜色列表。我得到了结果,但无论我多么努力都无法以正确的顺序得到结果,以便我可以写入一个文件,该文件又将用于另一个程序。所以,请帮忙。下面是代码。
# 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
解决方案
您可以组合两个列表,因为它们的长度匹配。我使用 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)
输出样本:
推荐阅读
- python - 无法导入通过 conda 离线安装的 python 包
- vue.js - 无法让地图与 highcharts-vue 一起使用
- import - 如何将格式化的 .csv 数据导入 SAS?
- prolog - 如何在第一个列表中保留在第二个列表中出现偶数的元素?(序言)
- php - 如何在来自 HTML 的 JSON AJAX 请求中添加滑块
- java - 在画廊 kotlin 上选择照片
- android - 设备进入某个位置时没有触发地理围栏
- instagram-api - 如何在可交付代码中验证 Instagram 应用程序?
- big-o - f(n) = f(n/3) + f(n-5) 的 BigO 表示法
- qooxdoo - qx.event.type.Event.addPromise() 是做什么用的?