我正在尝试从网站https://www.cellartracker.com/m/wines/12344 中抓取一些数据。我无法理解如何获取不属于标签中任何类的每个值。以下是我正在寻找的网站代码:<ul class="twin-set-list"> <li><span>Vintage</span> 2000</li> <li><span>Type</span> Red</li> <li><span>Producer</span> Balnaves of Coonawarra</li> <li><span>Varietal</span> Cabernet Sauvignon</li> <li><span>Designation</span> The Tally Reserve</li> <li><span>Vineyard</span> n/a</li> <li><span>Country</span> Australia</li> <li><span>Region</span> South Australia</li> <li><span>SubRegion</span> Limestone Coast</li> <li><span>Appellation</span> Coonawarra</li> </ul>像 2000、Red 等值没有任何类,所以我可以使用什么方式来获取数据。我在 python 中尝试了以下代码(下面仅给出了 html 部分): from bs4 import BeautifulSouphtml = """<ul class="twin-set-list"> <li><span>Vintage</span> 2000</li> <li><span>Type</span> Red</li> <li><span>Producer</span> Balnaves of Coonawarra</li> <li><span>Varietal</span> Cabernet Sauvignon</li> <li><span>Designation</span> The Tally Reserve</li> <li><span>Vineyard</span> n/a</li> <li><span>Country</span> Australia</li> <li><span>Region</span> South Australia</li> <li><span>SubRegion</span> Limestone Coast</li> <li><span>Appellation</span> Coonawarra</li> </ul>"""soup = BeautifulSoup(html, 'html.parser')need = {}for li_tag in soup.find_all('ul', {'class':'twin-set-list'}): for span_tag in li_tag.find_all('li'): field = span_tag.find('span').text value = span_tag.find('span').text need[field] = valueprint(need)谁能建议我如何提取这些数据?
3 回答
狐的传说
TA贡献1804条经验 获得超3个赞
您可以通过以下方式替换您的代码:
field = span_tag.find('span').text
value = span_tag.text.replace(field,'')
它不是很干净,但它适用于您的代码。
慕桂英4014372
TA贡献1871条经验 获得超13个赞
您可以遍历对象的contents
属性bs4
:
from bs4 import BeautifulSoup as soup d = [[getattr(c, 'text', c).strip() for c in i] for i in soup(html, 'html.parser').find_all('li')]
输出:
[['Vintage', '2000'], ['Type', 'Red'], ['Producer', 'Balnaves of Coonawarra'], ['Varietal', 'Cabernet Sauvignon'], ['Designation', 'The Tally Reserve'], ['Vineyard', 'n/a'], ['Country', 'Australia'], ['Region', 'South Australia'], ['SubRegion', 'Limestone Coast'], ['Appellation', 'Coonawarra']]
一只甜甜圈
TA贡献1836条经验 获得超5个赞
也许你可以试试这个:
for li_tag in soup.find_all('ul', {'class':'twin-set-list'}):
for span_tag in li_tag.find_all('li'):
field = span_tag.find('span').text
value = span_tag.text
value = value[len(field)+1:]
need[field] = value
以防万一,如果您在“值”中有相同的字段,请不要替换它,而是使用 subtring。
添加回答
举报
0/150
提交
取消