首页 > 解决方案 > Beautiful Soup 大部分标签都找不到

问题描述

我正在尝试抓取此页面https://ntrs.nasa.gov/search。我正在使用下面的代码,当有更多标签时,Beautiful soup 只找到 3 个标签。我尝试过使用 html5lib、lxml 和 HTML 解析器,但它们都没有奏效。

你能告诉我可能是什么问题吗?

import requests
import urllib.request
import time
from bs4 import BeautifulSoup

# Set the URL
url = 'https://ntrs.nasa.gov/search'

# Connect to the URL
response = requests.get(url)

# Parse HTML and save to a BeautifulSoup object¶
soup = BeautifulSoup(response.content, "html5lib")

# soup = BeautifulSoup(response.text, "html5lib")
# soup = BeautifulSoup(response.content, "html.parser")
# soup = BeautifulSoup(response.content, "lxml")

# loop through all a-tags
for a_tag in soup.findAll('a'):
    if 'title' in a_tag:
        if a_tag['title'] == 'Download Document':
            link = a_tag['href']
            download_url = 'https://ntrs.nasa.gov' + link
            urllib.request.urlretrieve(download_url,'./'+link[link.find('/citations/')+1:11])

标签: pythonbeautifulsoup

解决方案


它是从script标签中动态提取的。您可以正则表达式包含下载 url 的 JavaScript 对象,处理 html 实体的一些字符串替换,解析为 json 然后提取所需的 url:

import requests, re, json

r = requests.get('https://ntrs.nasa.gov/search')
data = json.loads(re.search(r'(\{.*/api.*\})', r.text).group(1).replace('&q;','"'))
print('https://ntrs.nasa.gov' + data['http://ntrs-proxy-auto-deploy:3001/citations/search']['results'][0]['downloads'][0]['links']['pdf'])

您可以附加,?attachment=true但我认为这不是必需的。


推荐阅读