【问题标题】:Scraping table returns only “table” and not the contents of the table抓取表只返回“表”而不是表的内容
【发布时间】:2020-08-18 10:39:23
【问题描述】:

图片描述在这里:

抓取表只返回“表”而不是表的内容。 这是我的code

from urllib.request import urlopen

from bs4 import BeautifulSoup

url = "http://data.eastmoney.com/gdhs/detail/600798.html"

html = urlopen(url)


soup = BeautifulSoup(html, 'lxml')

table = soup.find_all('table')

print(table)

【问题讨论】:

    标签: python beautifulsoup urlopen


    【解决方案1】:

    您发现表格与代码配合得很好。因为表格是由多个元素(tr/td)组成的,所以您必须遍历这些元素才能获取表格单元格的内部文本。

    # This grabs the first occurrence of a table on the web page. If you want the second occurrence of a table on the web page, use soup.find_all('table')[1], etc.
    
    table = soup.find_all('table')[0]
    
    # Use a splice if there are table headers. If you want to include the table headers, use table('tr')[0:]
    
    for row in table('tr')[1:]:
        print(row('td')[0].getText().strip())
    

    【讨论】:

    • 谢谢!但是上面的代码最后仍然没有打印出来。 “table('tr')”中没有显示任何内容,但“[]”中没有显示任何内容。
    • 我现在明白了。我去了网页并检查了源代码。看起来层次结构如下:
      。所以你要做的是table_body = table('tbody'),然后做for row in table_body('tr')[0:]: 并保留打印语句。我无法确认这是否有效,但应该会有所帮助。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-15
    • 2019-07-10
    • 1970-01-01
    • 2016-02-01
    相关资源
    最近更新 更多