python - Python:无法按属性搜索
问题描述
我正在尝试访问一个巨大的 html 文件中的表。该表在目录中引用。所以,我编写了代码来获取href。然后我使用 href 值来定位表。它有时会起作用。否则,它不返回任何内容。这是 html 摘录: 目录:
<a href="#h54"><font size="2">Summary Compensation Table</font></a>
表格位置在此标签下方:
<a name="h54"></a>
这是我的代码:
def your_filter(tag, value):
return any(tag[key] == value for key in tag.attrs.keys())
all_linked = soup.find_all("a", text=re.compile(r'summary compensation', re.IGNORECASE), href=True)
if len(all_linked)>0:
table_link = all_linked[0]['href']
tags = soup.find_all(lambda tag: your_filter(tag, table_link[1:]))
goto_table = soup.find(tags[0].name, tags[0].attrs)
这里的标签没有返回。
解决方案
DOM 非常“扁平”,当您实际上需要在 DOM 更高层、位于父 div 之一的级别,然后寻找div
具有目标表的兄弟姐妹时,您会找到一个嵌套元素。一种方法可能如下:
import requests
from bs4 import BeautifulSoup as bs
from pandas import read_html as rh
r = requests.get('https://www.sec.gov/Archives/edgar/data/72741/000104746918002070/a2234804zdef14a.htm', headers = {'User-Agent': 'Mozilla/5.0'})
soup = bs(r.content, 'lxml')
df = rh(str(soup.select_one('div:has(b:-soup-contains("SUMMARY COMPENSATION TABLE")) ~ div div > table')))[0]
df.dropna(how='all', axis = 1, inplace = True)
df.columns = df.iloc[1, :]
df = df.iloc[3:, :]
df.reset_index(drop=True, inplace = True)
df
推荐阅读
- c - Mad_Flute 在 65535 块后停止接收
- c++ - How safe is using an std::atomic
index to asynchronously parallelize operation on large array - azure - 将 Azure SQL DB 长期备份存储在另一个订阅中
- python - Only obtain p-value from t-test error when selecting subset
- c# - 如何连接桌面应用程序和浏览器?
- java - Add and remove Spring Boot health checks dynamically
- android - 使用我的应用程序 + xamarin android 打开任何 .jpg 图像
- windows-10 - 品牌化 Windows 10
- html - Collapse Left Sidebar fully in ShinyDashboardPlus
- go - What is the most idiomatic way to mimic inheritance in Go in this specific case?