python - 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])
解决方案
它是从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
但我认为这不是必需的。
推荐阅读
- typescript - 用于只读 useState 的 Typescript 包装函数
- javascript - 通过存储在数组 p5.js 中的点创建正方形
- r - 我应该如何解决错误“没有名为'rspatial'的包?
- iteration - 确定何时停止可能的无限迭代?
- python - 如何递归地将返回列表的芹菜任务链接到组中?
- css - CSS:删除框之间的空白空间
- javascript - 如何在我的 Redux 应用程序中实现这些备注?
- javascript - 获取已更改的属性列表?
- java - 执行删除语句时休眠抛出ConstraintViolationException
- javascript - 使用 React Hooks 和 Redux 重新渲染的次数过多