簡體   English   中英

用美麗的湯解析HTML span

[英]Parsing HTML span with Beautiful Soup

我試圖弄清楚如何使用美麗湯,並且遇到了困難。

我的HTML頁面具有以下幾個元素:

<a class="propertyName" href="/preferredguest/property/overview/index.html?propertyID=1023"><span>The Westin Peachtree Plaza, Atlanta
</span></a>

<a class="propertyName" href="/preferredguest/property/overview/index.html?propertyID=1144"><span>Sheraton Atlanta Hotel
</span></a>

我正在嘗試使用酒店名稱創建一個數組。 到目前為止,這是我的代碼:

import requests
from bs4 import BeautifulSoup

url = "removed"
response = requests.get(url)
soup = BeautifulSoup(response.text)

hotels = soup.find_all('a', class_="propertyName")

但是我不知道如何遍歷Hotels數組以顯示span元素。

您的“旅館”名稱在span 一種方法是使用.select()方法

>>> from bs4 import BeautifulSoup
>>> soup = BeautifulSoup('''<a class="propertyName" href="/preferredguest/property/overview/index.html?propertyID=1023"><span>The Westin Peachtree Plaza, Atlanta
... </span></a>
... 
... <a class="propertyName" href="/preferredguest/property/overview/index.html?propertyID=1144"><span>Sheraton Atlanta Hotel
... </span></a>
... ''', 'lxml')
>>> [element.get_text(strip=True) for element in soup.select('a.propertyName > span')]
['The Westin Peachtree Plaza, Atlanta', 'Sheraton Atlanta Hotel']
>>> 

要么

>>> names = []
>>> for el in hotels:
...     names.append(el.find('span').get_text(strip=True))
... 
>>> names
['The Westin Peachtree Plaza, Atlanta', 'Sheraton Atlanta Hotel']
>>> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM