【问题标题】:web scraping using beautifulsoup: separating values使用 beautifulsoup 进行网页抓取:分离值
【发布时间】:2015-09-07 20:41:06
【问题描述】:

我使用 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)

我可以只收集名字吗?那么从属信息分开呢?提前致谢。

【问题讨论】:

    标签: python python-2.7 beautifulsoup


    【解决方案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)')]
    

    【讨论】:

      【解决方案2】:

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

      【讨论】:

      • 这行得通...谢谢...我将“item”更改为“item.text”
      猜你喜欢
      • 2018-08-02
      • 1970-01-01
      • 2020-10-04
      • 2021-01-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-10
      相关资源
      最近更新 更多