2016-01-24 149 views
0

我想弄清楚如何使用美麗的湯,我很難。美麗的湯解析HTML跨度

我的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") 

但我無法弄清楚如何迭代酒店數組顯示span元素。

回答

2

您的「酒店」名稱在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'] 
>>>