鉴于我的代码:
browser.get(s_page_url)
soup = BeautifulSoup(browser.page_source, "html.parser")
s_image_element = soup.find('a', {'id': 'angle-3'})
s_image_href = s_image_element['href']
s_image_url = "http://www.zappos.com" + s_image_href
s_title_element = soup.find('h1', {'class': 'banner'})
print s_title_element
目前产生以下输出:
<h1 class="banner">
<a href="http://couture.zappos.com/a-testoni">a. testoni</a>
<meta content="a. testoni" itemtype="brand">
<a href="/p/a-testoni-sport-nappa-calf-sneaker/product/8835012"><span class="ProductName" itemprop="name">Sport Nappa Calf Sneaker</span></a>
</meta></h1>
我如何获取<a href="http://couture.zappos.com/a-testoni">a. testoni</a>
中的文字,即a. testoni
和<span class="ProductName" itemprop="name">Sport Nappa Calf Sneaker</span>
,即Sport Nappa Calf Sneaker
?
到目前为止,我已尝试过以下内容:
print s_title_element['a']
但是请收到以下错误消息:
File "C:\Python27\lib\site-packages\bs4\element.py", line 958, in __getitem__
return self.attrs[key]
KeyError: 'a'
答案 0 :(得分:1)
print s_title_element.get_text(strip=True,separator=" " )
get_text
将连接标记对象中的所有文本。 strip=True
将在开头和结尾删除空格
def get_text(self, separator="", strip=False,
types=(NavigableString, CData)):
"""
Get all child strings, concatenated using the given separator.