【问题标题】:Table attribute meanings in BeautifulSoupBeautifulSoup 中的表属性含义
【发布时间】:2021-03-27 13:33:54
【问题描述】:

对于使用beautifulsoup 的项目,我需要从该站点https://www.macrotrends.net/stocks/charts/TSLA/tesla/revenue 获取“特斯拉季度收入”表。我认为我准确地获取了初始 html 数据,但我不确定“Tesla Quarterly Revenue”这个短语附加到哪个标签,我认为它可能在 thead 下但不会输出表格。

r=requests.get( 'https://www.macrotrends.net/stocks/charts/TSLA/tesla/revenue')
html_data=r.text
soup=BeautifulSoup(html_data)
#print(soup.prettify())
table_=soup.find_all('thead','Tesla Quarterly Revenue')
table_row=table_.find_all('tr')
for row in table_row:
    col = row.find_all("td")
    date =col[0].text
    revenue =col[1].text
    tesla_revenue = tesla_revenue.append({"Date":date, "Revenue":revenue}, ignore_index=True)

tesla_revenue.head()

这里的汤输出

 <div class="col-xs-6">
       <table class="historical_data_table table">
        <thead>
         <tr>
          <th colspan="2" style="text-align:center">
           Tesla Quarterly Revenue
           <br/>
           <span style="font-size:14px;">
            (Millions of US $)
           </span>
          </th>
         </tr>
        </thead> 

我知道我可以选择整个区域使用

soup.find_all('div',class_='col-xs-6') 

但是这个标签下有多个表格,我不确定如何进一步完善它。感谢您的帮助。

【问题讨论】:

  • 我认为我可以通过这种方式抓取桌子 table_=soup.find_all('table') table_=table_[1] ,但这需要在多个点进行检查才能获得桌子编号(并且知道它的存在)

标签: python html python-3.x beautifulsoup


【解决方案1】:

它在表头中。您可以使用以下 css 选择器抓取

soup.select_one('#style-1 div + div .historical_data_table th')

如果你只想要第一行,你可以使用 stripped_strings 和 index 0:

[s for s in soup.select_one('#style-1 div + div .historical_data_table th').stripped_strings][0]

由于有多个类historical_data_table 的表,上面的选择器使用id 为style-1 的元素作为锚点,移动到类historical_data_table 的表,它是div 的子元素,即另一个div 的直系兄弟姐妹,这是该锚点的孩子;然后它移动到该表的子th

【讨论】:

    【解决方案2】:

    你应该先选择main_content div,然后选择里面的表,最后找到正确的表。 此代码将帮助您找到正确的 tbody:

    r=requests.get( 'https://www.macrotrends.net/stocks/charts/TSLA/tesla/revenue')
    html_data=r.text
    soup=BeautifulSoup(html_data)
    main = soup.find('div',id = 'main_content')
    tables = main.find_all('table', class_='historical_data_table table')
    table_ = ''
    for table in tables:
        if table.text.find('Tesla Quarterly Revenue') >= 0:
            table_ = table
            break
    table_ = table_.find('tbody')
    
    table_row=table_.find_all('tr')
    

    【讨论】:

    • 谢谢,这似乎是我所追求的!为什么在for循环之前创建空table_对象,是为了防止找不到表就报错吗?
    猜你喜欢
    • 1970-01-01
    • 2022-07-18
    • 1970-01-01
    • 1970-01-01
    • 2017-09-07
    • 2011-11-27
    • 1970-01-01
    • 1970-01-01
    • 2021-04-09
    相关资源
    最近更新 更多