python - 在 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,或者这是否可能。
任何人都可以提供任何信息吗?
罗斯
解决方案
你可以使用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
推荐阅读
- ionic3 - 地理位置 - 如果我从启用 GPS 开始,Ionic 3 天气应用程序可以正常工作
- python - mpiexec + python + ^C: __del__ 方法未执行(并且没有回溯)
- mysql - 如何处理 SQL (mySQL) 中的非标准日期格式?
- c# - 为什么 EF Core 不自动生成 id 字段?
- c# - 使用 C#、.NET Core 3 和 GTK# 进行跨平台编程(和替代方案)
- r - 如何根据 R 中的多个条件正确定义新列
- javascript - 为什么 Proxy 对象反映的变化超出了目标对象?
- aws-lambda - SAM 允许访问 Cognito
- r - R代码:当我在R中绘制包含多条线的折线图时,其中一条无法完全显示
- android - Android 动态交付:无法解析以下类的超类型;未解决的超类型:android:support:v7:app:AppCompatActivity