python - 使用 Beautifulsoup 进行网页抓取并收集表格文本值
问题描述
我的代码如下,它从 NSE 网站收集数据。基本上我想收集2个信息:
- 什么是
Announcement
主题- 检查是否有任何
我能够获得 pdf 链接,但无法阅读
Announcement
主题MIC Electronics Limited 已就“M/s.的解决方案”通知联交所。Cosyn Consortium 处理 M/s 问题。MIC Electronics Limited 已获得 Hon'ble NCLT, Hyderabad Bench 的批准
任何帮助。
import requests
import json
import bs4
base_url = 'https://www.nseindia.com'
url = 'https://www.nseindia.com/corporates/directLink/latestAnnouncementsCorpHome.jsp'
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36'}
response = requests.get(url, headers=headers)
jsonStr = response.text.strip()
keys_needing_quotes = ['company:','date:','desc:','link:','symbol:']
for key in keys_needing_quotes:
jsonStr = jsonStr.replace(key, '"%s":' %(key[:-1]))
data = json.loads(jsonStr)
data = data['rows']
# print(data)
symbol_list = ['MIC']
for x in range(0, len(data)):
if data[x]['symbol'] in symbol_list:
response = requests.get(base_url + data[x]['link'], headers=headers)
soup = bs4.BeautifulSoup(response.text, 'html.parser')
print(soup)
try:
pdf_file = base_url + soup.find_all('a', href=True)[0]['href']
print("File_Link:", pdf_file)
except:
print('PDF not found')
解决方案
或者您可以使用:
for s in soup.find_all('td', 'tablehead'):
if 'Announcement' in s.text:
break
print(s.find_next_sibling().text))
# output:
# MIC Electronics Limited has informed the Exchange regarding 'Resolution Plan of M/s. Cosyn Consortium in the matter of M/s. MIC Electronics Limited has been approved by Hon'ble NCLT, Hyderabad Bench
推荐阅读
- django - django 中的用户类型
- c - 进行条件语句时如何使用argv的ascii代码?
- delphi - Delphi 正确签名 LowLevelKeyboardProc()
- fetch - 获取失败时如何获得更明确的错误消息?
- python - 在 python 中使用 for 循环遍历文本文件 - 为什么会这样?
- python - 当没有“更多”按钮时,向下滚动到网页末尾时,单击使用 python selenium 动态加载的链接
- node.js - 对于模型“modelName”的路径“_id”处的值“{ populate: [] }”,转换为 ObjectId 失败。NodeJS 猫鼬
- azure - 将 VM 映像复制到 Blob 存储
- excel - 使用 Excel 条件格式检查日期
- c++ - 在 C/C++ 中将数组作为形式参数作为 int arr[] 和 int arr[N] 传递的区别