无法使用BeautifulSoup解析表

时间:2016-08-26 13:52:53

标签: python html parsing beautifulsoup inspect-element

我一直在尝试使用table id =" tblDataset2"解析表here。并尝试访问表中的行,但是当我使用beautifulsoup解析网页时,我只获得一行。 这是我的代码:

from bs4 import BeautifulSoup
import requests

URL = 'http://podaac.jpl.nasa.gov/ws/'
dataset_ids = []
html = requests.get(URL + 'search/granule/index.html')
soup = BeautifulSoup(html.text, 'html.parser')

table = soup.find("table", {"id": "tblDataset2"})
rows = table.find_all('tr')
rows.remove(rows[0])
print table
for row in rows:
    x = row.find_all('td')
    dataset_ids.append(x[0].text.encode('utf-8'))

print dataset_ids

我想访问表格的所有行。请帮我解决一下这个。感谢。

1 个答案:

答案 0 :(得分:1)

浏览器从另一个返回JSON响应的端点异步加载此特定数据集。直接向该端点发出请求:

import requests

URL = 'http://podaac.jpl.nasa.gov/l2ssIngest/datasets'
response = requests.get(URL)
data = response.json()

for item in data["datasets"]:
    print(item["persistentId"], item["shortName"])

打印:

(u'PODAAC-AQR40-2SOCS', u'AQUARIUS_L2_SSS_V4')
(u'PODAAC-QSX12-L2B01', u'QSCAT_LEVEL_2B_OWV_COMP_12')
(u'PODAAC-ASOP2-12C01', u'ASCATA-L2-Coastal')
(u'PODAAC-ASOP2-25X01', u'ASCATA-L2-25km')
(u'PODAAC-ASOP2-25B01', u'ASCATB-L2-25km')
(u'PODAAC-ASOP2-COB01', u'ASCATB-L2-Coastal')
(u'PODAAC-J2ODR-GPS00', u'OSTM_L2_OST_OGDR_GPS')
(u'PODAAC-OSCT2-L2BV2', u'OS2_OSCAT_LEVEL_2B_OWV_COMP_12_V2')
(u'PODAAC-RSX12-L2B11', u'RSCAT_LEVEL_2B_OWV_COMP_12_V1.1')
(u'PODAAC-AKASA-XOGD1', u'ALTIKA_SARAL_L2_OST_XOGDR')
(u'PODAAC-GHAM2-2PR72', u'AMSR2-REMSS-L2P-v7.2')
(u'PODAAC-GHVRS-2PN01', u'VIIRS_NPP-NAVO-L2P-v2.0')
(u'PODAAC-RSX12-L2B12', u'RSCAT_LEVEL_2B_OWV_COMP_12_V1.2')

对于第一个数据集,您需要向“搜索”端点发出GET请求:

from operator import itemgetter

import requests


URL = 'http://podaac.jpl.nasa.gov/dmasSolr/solr/dataset/select/'
response = requests.get(URL, params={
    'q': '*:*',
    'fl': 'Dataset-PersistentId,Dataset-ShortName-Full',
    'rows': '2147483647',
    'fq': 'DatasetPolicy-AccessType-Full:(OPEN OR PREVIEW OR SIMULATED OR REMOTE) AND DatasetPolicy-ViewOnline:Y',
    'wt': 'json'
})
data = response.json()

for doc in sorted(data['response']['docs'], key=itemgetter('Dataset-ShortName-Full')):
    print(doc['Dataset-PersistentId'], doc['Dataset-ShortName-Full'])

打印:

(u'PODAAC-GHRAM-4FA01', u'ABOM-L4HRfnd-AUS-RAMSSA_09km')
(u'PODAAC-GHGAM-4FA01', u'ABOM-L4LRfnd-GLOB-GAMSSA_28km')
(u'PODAAC-AKASA-XOGD1', u'ALTIKA_SARAL_L2_OST_XOGDR')
(u'PODAAC-USWCO-ALT01', u'ALT_TIDE_GAUGE_L4_OST_SLA_US_WEST_COAST')
...
(u'PODAAC-SASSX-L2WAF', u'WAF_DEALIASED_SASS_L2')
(u'PODAAC-SMMRN-2WAF0', u'WENTZ_NIMBUS-7_SMMR_L2')
(u'PODAAC-SASSX-L2SN0', u'WENTZ_SASS_SIGMA0_L2')

如果您不想深入了解页面的加载和形成方式,可以使用selenium自动生成的真实浏览器。