gpt4 book ai didi

python - 无法按正确顺序排列网络解析结果

转载 作者:太空狗 更新时间:2023-10-30 02:51:08 25 4
gpt4 key购买 nike

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

# 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]')).我为 rgbs 列表中的每个元素提取 title 属性,然后用正则表达式输出所需的字符串。我只是将 .text 用于 colours 列表中返回的 a 标记子项。

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)

输出示例:

enter image description here

关于python - 无法按正确顺序排列网络解析结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57116627/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com