在Python中进行web抓取时,如何引用特定ID?

在Python中进行web抓取时,如何引用特定ID?,python,web-scraping,data-science,data-collection,Python,Web Scraping,Data Science,Data Collection,我正试图从网站上获取基本的股票信息: 我的代码如下: 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

我正试图从网站上获取基本的股票信息:

我的代码如下:

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,或者如果可能的话

有人能提供任何信息吗

Ross

您可以用于此工作:

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

这是因为浏览器使用java脚本生成表的html内容,因此请求模块返回的html不包含html代码,而是包含用于生成它的java脚本代码。解决方法是使用基于浏览器的报废工具,如selenium。查看此链接了解更多信息