![](/img/trans.png)
[英]How can I get the second span using BeautifulSoup in python?
[英]How to get span value using python,BeautifulSoup
我是第一次使用BeautifulSoup,並嘗試從湯對象中收集一些數據,例如電子郵件,電話號碼和郵寄地址。
使用正則表達式,我可以識別電子郵件地址。 我找到電子郵件的代碼是:
def get_email(link):
mail_list = []
for i in link:
a = str(i)
email_pattern = re.compile("<a\s+href=\"mailto:([a-zA-Z0-9._@]*)\">", re.IGNORECASE)
ik = re.findall(email_pattern, a)
if (len(ik) == 1):
mail_list.append(i)
else:
pass
s_email = str(mail_list[0]).split('<a href="')
t_email = str(s_email[1]).split('">')
print t_email[0]
現在,我還需要收集電話號碼,郵寄地址和網址。 我認為在BeautifulSoup中,必須有一種簡單的方法來查找這些特定數據。
一個示例html頁面如下:
<ul>
<li>
<span>Email:</span>
<a href="mailto:abc@gmail.com">Message Us</a>
</li>
<li>
<span>Website:</span>
<a target="_blank" href="http://www.abcl.com">Visit Our Website</a>
</li>
<li>
<span>Phone:</span>
(123)456-789
</li>
</ul>
並使用BeatifulSoup,我試圖收集電子郵件,網站和電話的跨度值。
提前致謝。
代碼最明顯的問題是,您將表示鏈接的對象重新轉換為HTML,然后再次使用正則表達式對其進行解析-首先,它忽略了使用BeautifulSoup的許多要點。 您可能需要使用正則表達式來處理href
屬性的內容,僅此而已。 另外, else: pass
是不必要的-您可以完全省略else: pass
。
這是一些執行所需操作的代碼,可能是一個有用的起點:
from BeautifulSoup import BeautifulSoup
import re
# Assuming that html is your input as a string:
soup = BeautifulSoup(html)
all_contacts = []
def mailto_link(e):
'''Return the email address if the element is is a mailto link,
otherwise return None'''
if e.name != 'a':
return None
for key, value in e.attrs:
if key == 'href':
m = re.search('mailto:(.*)',value)
if m:
return m.group(1)
return None
for ul in soup.findAll('ul'):
contact = {}
for li in soup.findAll('li'):
s = li.find('span')
if not (s and s.string):
continue
if s.string == 'Email:':
a = li.find(mailto_link)
if a:
contact['email'] = mailto_link(a)
elif s.string == 'Website:':
a = li.find('a')
if a:
contact['website'] = a['href']
elif s.string == 'Phone:':
contact['phone'] = unicode(s.nextSibling).strip()
all_contacts.append(contact)
print all_contacts
這將為找到的每個聯系人生成一個詞典列表,在這種情況下,將為:
[{'website': u'http://www.abcl.com', 'phone': u'(123)456-789', 'email': u'abc@gmail.com'}]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.