首页 > 解决方案 > 在 Python 中进行网络抓取时如何引用特定 ID?

问题描述

我正在尝试通过网络抓取该网站以获取基本的股票信息:https ://www.macrotrends.net/stocks/charts/AAPL/apple/financial-ratios

我的代码如下:

from requests import get
from bs4 import BeautifulSoup as bs

url =  'https://www.macrotrends.net/stocks/charts/AAPL/apple/financial-ratios'
response = get(url)
html_soup = bs(response.text, 'html.parser')

stock_container = html_soup.find_all("div", attrs= {'id': 'row0jqxgrid'})


print(len(stock_container))

现在我慢慢来,只是试图在 id 名称“row0jqxgrid”下返回“div”的数量。我很确定第 8 行之前的一切都很好,但我不知道如何使用 attrs 正确引用 id,或者这是否可能。

任何人都可以提供任何信息吗?

罗斯

标签: pythonweb-scrapingdata-sciencedata-collection

解决方案


你可以使用selenium 来完成这项工作:

from selenium import webdriver
import os


# define path to chrome driver
chrome_driver = os.path.abspath(os.path.dirname(__file__)) + '/chromedriver'
browser = webdriver.Chrome(chrome_driver)
browser.get("https://www.macrotrends.net/stocks/charts/AAPL/apple/financial-ratios")

# get row element
row = browser.find_element_by_xpath('//*[@id="row0jqxgrid"]')

# find all divs currently displayed
divs_list = row.find_elements_by_tag_name('div')

# get text from cells
for item in divs_list:
    print(item.text)

输出:

输出文本加倍,因为当您向右移动底部滚动条时会动态加载表格数据。

Current Ratio
Current Ratio
1.5401
1.5401
1.1329
1.1329
1.2761
1.2761
1.3527
1.3527
1.1088
1.1088
1.0801
1.0801

推荐阅读