我试图使用BeautifulSoup和d requests库从维基百科获取颜色列表。我得到了结果,但无论我多么努力,都无法按正确的顺序得到结果,这样我就可以将其写入一个文件中,而该文件又将用于另一个程序。所以请帮帮忙。下面是密码。
# 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发布于 2019-07-19 17:38:56
捕获包装2个p标记的div,使用文本作为颜色名称,然后解析每个div的第一个p标记的样式属性中的rgb值,然后得到您想要的输出。
divs = soup.find_all('div', style="float:left;display:inline;font-size:90%;margin:1px 5px 1px 5px;width:11em; height:6em;text-align:center;padding:auto;")
for i in divs:
color_value = i.find('p').get('style').split('rgb(')[1].split(')')[0]
color_value = color_value.replace(',', ' ').strip()
print(color_value, i.text.strip())发布于 2019-07-19 18:07:15
您可以组合两个列表,因为它们在长度上匹配。我使用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)输出示例:

发布于 2019-07-19 19:01:30
另一种方法就是--别再犯了!
soup = BeautifulSoup(r.text, 'html.parser')
dat = []
dat2 = []
for i in soup.find_all('p'):
if i.get('title') is not None:
title = i.get('title').split('\n')[1].replace(' (','').replace(')','')
dat.append(title)
if len(i.text.strip())>0:
dat2.append(i.text)
del dat2[0]
for i, j in zip (dat,dat2):
print(i,j)输出:
0 72 186 Absolute Zero
176 191 26 Acid green
124 185 232 Aero等。
https://stackoverflow.com/questions/57116627
复制相似问题