【问题标题】:Beautiful Soup can't find most of the tagsBeautiful Soup 找不到大部分标签
【发布时间】:2021-09-03 06:06:11
【问题描述】:

我正在尝试抓取此页面 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])

【问题讨论】:

  • 如果在浏览器中找不到带有 BS 的元素,则可能是页面正在使用 JavaScript 动态加载。见Web-scraping JavaScript page with Python。我建议使用requests_html 或selenium。

标签: python beautifulsoup


【解决方案1】:

它是从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,但我认为这不是必需的。

【讨论】:

    【解决方案2】:

    你的问题源于页面是使用Javascipt渲染的,实际页面源只有几个script和style标签。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-08-20
      • 1970-01-01
      • 1970-01-01
      • 2019-01-29
      • 2013-07-15
      相关资源
      最近更新 更多