【发布时间】: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”响应。
【问题讨论】:
-
您可能需要
if datetime.today().strftime('%Y') in soup2.findAll('a'):而不是…soup2.get('a')。 -
无论如何,它不会工作。像
Oct 24 04:42 UTC这样的字符串不是任何 标记的一部分,它只是 标记之前的文本。你必须找到这个文本,然后找到它后面的标签。
标签: python python-2.7 beautifulsoup