【问题标题】:Best way to get 'hrefs' from CSS selector in BeautifulSoup?从 BeautifulSoup 中的 CSS 选择器获取“hrefs”的最佳方法?
【发布时间】:2016-02-08 21:03:11
【问题描述】:

编写一个脚本,最初将抓取给定人口普查区块组中所有人口普查区块的数据。不过,为了做到这一点,我首先需要能够获得给定区域中所有块组的链接。这些区域由带有指向它们的 URL 的列表定义,该列表返回一个页面,该页面列出了 css 选择器“div#rList3 a”中的块组。当我运行这段代码时:

from bs4 import BeautifulSoup
from urllib.request import urlopen

tracts = ['http://www.usa.com/NY023970800.html','http://www.usa.com/NY023970900.html',
       'http://www.usa.com/NY023970600.html','http://www.usa.com/NY023970700.html',
       'http://www.usa.com/NY023970500.html']

class Scrape:
    def scrapeTracts(self):
        for i in tracts:
            html = urlopen(i)
            soup = BeautifulSoup(html.read(), 'lxml')
            bgs = soup.select("div#rList3 a")
            print(bgs)

s = Scrape()
s.scrapeTracts()

这给了我一个看起来像这样的输出:[<a href="/NY0239708001.html">NY0239708001</a>](为了这篇文章的篇幅,链接的实际数量被剪掉了。)我的问题是,我怎样才能得到 just 'href' 之后的字符串,在本例中为 /NY0239708001.html?

【问题讨论】:

标签: python css beautifulsoup


【解决方案1】:

您可以通过以下方式在一行中完成此操作:

bgs = [i.attrs.get('href') for i in soup.select("div#rList3 a")]

输出:

['/NY0239708001.html']
['/NY0239709001.html', '/NY0239709002.html', '/NY0239709003.html', '/NY0239709004.html']
['/NY0239706001.html', '/NY0239706002.html', '/NY0239706003.html', '/NY0239706004.html']
['/NY0239707001.html', '/NY0239707002.html', '/NY0239707003.html', '/NY0239707004.html', '/NY0239707005.html']
['/NY0239705001.html', '/NY0239705002.html', '/NY0239705003.html', '/NY0239705004.html']

【讨论】:

  • 真棒单线!谢谢@idjaw!
【解决方案2】:

每个节点都有一个 attrs 字典,其中包含该节点的属性...包括 CSS 类,或者在本例中为 href。

hrefs = []
for bg in bgs:
    hrefs.append(bg.attrs['href'])

【讨论】:

  • 你可以让它更简单:hrefs = [bg['href'] for bg in bgs].
猜你喜欢
  • 2011-01-10
  • 1970-01-01
  • 2016-10-18
  • 1970-01-01
  • 2010-10-27
  • 1970-01-01
  • 1970-01-01
  • 2015-01-04
  • 2010-12-23
相关资源
最近更新 更多