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

时间:2015-09-07 20:41:06

标签: python python-2.7 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)

我可以只收集名字吗?然后单独的附属信息?提前谢谢。

2 个答案:

答案 0 :(得分:1)

您可以使用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,同样做。

答案 1 :(得分:1)

您可以使用:

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)')]