使用beautifulsoup进行网页抓取:分离值



我用beautifulsoup做网页抓取。该网页的来源如下:

<a href="/en/Members/">
                            Courtney, John  (Dem)                       </a>,
<a href="/en/Members/">
                            Clinton, Hilary  (Dem)                      </a>,
<a href="/en/Members/">
                            Lee, Kevin  (Rep)                       </a>,

下面的代码可以工作。

for item in soup.find_all("a"):
    print item

但是,代码返回以下内容:

Courtney, John  (Dem)
Clinton, Hilary  (Dem)
Lee, Kevin  (Rep)

我可以只收集名字吗?那么分别是隶属关系信息吗?

您可以使用:

from bs4 import BeautifulSoup
content = '''
<a href="/en/Members/">Courtney, John  (Dem)</a>
<a href="/en/Members/">Clinton, Hilary  (Dem)</a>,
<a href="/en/Members/">Lee, Kevin  (Rep)</a>
'''
politicians = []
soup = BeautifulSoup(content)
for item in soup.find_all('a'):
    name, party = item.text.strip().rsplit('(')
    politicians.append((name.strip(), party.strip()[:-1])) 

由于名称和隶属关系信息都构成了a标签的文本内容,所以不能单独收集。你必须把它们串在一起,然后分开。我已经使用strip()函数来删除不需要的空白,并使用rsplit('(')函数来分割左括号上出现的文本内容。

print(politicians)
[(u'Courtney, John', u'Dem)'),
 (u'Clinton, Hilary', u'Dem)'),
 (u'Lee, Kevin', u'Rep)')]

您可以使用re.split()在多个分隔符上分割字符串,方法是制作要分割的正则表达式模式。这里我拆分了()

import re
for item in soup.find_all("a"):
    tokens = re.split('(|)', item)
    name = tokens[0].strip()
    affiliation = tokens[1].strip()
    print name
    print affiliation

来源:https://docs.python.org/2/library/re.html re.split

re.split()将返回如下所示的列表:

>>> re.split('(|)', item)
['Courtney, John  ', 'Dem', '']

从列表中获取条目0作为名称,去掉末尾的空白。抓取条目1作为从属关系,做同样的事情。

最新更新