我正在嘗試撰寫一些代碼,從股票篩選網站上的表格中抓取不同的資料并將資料保存在 excel 中。我遇到的問題是我想從表中提取的某些值沒有明確的類代碼。所以我只為我想要的第一個標題嘗試了這個,但它會拉出頁面上的所有標簽鏈接。任何幫助,將不勝感激?
from bs4 import BeautifulSoup
import requests
import pandas as pd
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:94.0) Gecko/20100101 Firefox/94.0'}
df_headers = ['Ticker' , 'Owner' , 'Relationshiop' , 'Date' ,'Transaction' , 'Total Shares' , 'SEC Form']
url= "https://finviz.com/insidertrading.ashx"
r = requests.get(url, headers=headers)
soup = BeautifulSoup(r.content, 'lxml')
Ticker = [item.text for item in soup.select('.tab-link:nth-of-type(1):not([id])')]
print(Ticker)
我也試過這段代碼Ticker = [item.text for item in soup.select('.insider-buy-row-2 .tab-link')],它確實拉出了我想要的代碼,但它還包括人名和其他行。
uj5u.com熱心網友回復:
使用pandas和的組合BeautifulSoup-
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:94.0) Gecko/20100101 Firefox/94.0'}
df_headers = ['Ticker' , 'Owner' , 'Relationshiop' , 'Date' ,'Transaction' , 'Total Shares' , 'SEC Form']
url= "https://finviz.com/insidertrading.ashx"
r = requests.get(url, headers=headers)
soup = BeautifulSoup(r.content, 'lxml')
tbl = soup.findAll("table")
tbls = pd.read_html(str(tbl))
df = tbls[4]
df, df.columns = df[1:] , df.iloc[0]
這里的重要部分是pd.read_html可以從<table>標簽中讀取多個資料幀。您只需要從輸出中獲取正確的表格并正確設定標題。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/354330.html
下一篇:網頁抓取時如何切換框?
