【问题标题】:BeautifulSoup Soup RecursiveBeautifulSoup 汤递归
【发布时间】:2016-11-06 16:14:57
【问题描述】:

我想递归检索网页的 url 并在列表中获取结果。

这是我正在使用的代码:

catalog_url = "http://nomads.ncep.noaa.gov:9090/dods/gfs_0p25/"

from bs4 import BeautifulSoup #  conda install -c asmeurer beautiful-soup=4.3.2 
import urllib2
from datetime import datetime

html_page = urllib2.urlopen(catalog_url)
soup = BeautifulSoup(html_page)

urls_day = []
for link in soup.findAll('a'):
    if datetime.today().strftime('%Y') in link.get('href'): # String contains today's year in name
        print link.get('href')
        urls_day.append(link.get('href'))

urls_final = []
for run in urls_day:
    html_page2 = urllib2.urlopen(run)
    soup2 = BeautifulSoup(html_page2)
    for links in soup2.findAll('a'):
        if datetime.today().strftime('%Y') in soup2.get('a'):
            print links.get('href')
            urls_final.append(links.get('href'))

在第一个循环中,我得到了catalog_url 中的网址。 urls_day 是一个列表对象,其 url 中包含当前年份的字符串。

第二个循环失败,输出如下:

<a href="http://nomads.ncep.noaa.gov:9090/dods">GrADS Data Server</a>
Traceback (most recent call last):
  File "<stdin>", line 6, in <module>
TypeError: argument of type 'NoneType' is not iterable

urls_final 应该是包含我感兴趣的 url 的列表对象。

知道如何解决它吗?我用递归检查过漂亮汤的类似帖子,但我总是得到相同的“NoneType”响应。

【问题讨论】:

标签: python python-2.7 beautifulsoup


【解决方案1】:

在调用递归函数之前,您应该检查返回值是否为 NoneType。我写了一个你可以改进的例子。

from bs4 import BeautifulSoup
from datetime import datetime
import urllib2

CATALOG_URL = "http://nomads.ncep.noaa.gov:9090/dods/gfs_0p25/"

today = datetime.today().strftime('%Y')

cache = {}


def cached(func):
    def wraps(url):
        if url not in cache:
            cache[url] = True
            return func(url)
    return wraps


@cached
def links_from_url(url):
    html_page = urllib2.urlopen(url)
    soup = BeautifulSoup(html_page, "lxml")
    s = set([link.get('href') for link in soup.findAll('a') if today in link.get('href')])
    return s if len(s) else url


def crawl(links):
    if not links:  # Checking for NoneType
        return
    if type(links) is str:
        return links
    if len(links) > 1:
        return [crawl(links_from_url(link)) for link in links]


if __name__ == '__main__':
    crawl(links_from_url(CATALOG_URL))
    print cache.keys()

【讨论】:

  • 恐怕这不能解决 OP 的问题。而且我不确定您的 cached 装饰器:如果 url 被缓存,它不会返回任何内容:是故意的吗?
猜你喜欢
  • 1970-01-01
  • 2018-08-13
  • 1970-01-01
  • 2021-06-16
  • 1970-01-01
  • 1970-01-01
  • 2018-06-30
  • 1970-01-01
  • 2018-05-08
相关资源
最近更新 更多