gpt4 book ai didi

python - 如何用Python选择网页的特定表格

转载 作者:太空宇宙 更新时间:2023-11-04 05:39:36 26 4
gpt4 key购买 nike

我是编程和 python 方面的新手。但我想在我的 python 脚本中解析 HTML。

这是网页: http://stock.finance.sina.com.cn/hkstock/finance/00759.html

问题 1:

本页是关于特定股份的财务信息。这四张表是关于:

  1. 财务摘要,
  2. Assets 负债表,
  3. 现金流
  4. 损益表。

我想提取表 3 和表 4 中的信息。这是我的代码:

import urllib
from bs4 import BeautifulSoup

url = 'http://stock.finance.sina.com.cn/hkstock/finance/00759.html'

html = urllib.urlopen(url).read() #.read() mean read all into a string
soup = BeautifulSoup(html, "lxml")

table = soup.find("table", { "class" : "tab05" })
for row in table.findAll("tr"):
print row.findAll("td")

但是这段代码只能得到第一个表的信息。如何更改代码以获取第三个和第四个表信息?我发现那 4 个表不包含唯一 ID 或类名,我不知道如何找到它们....

问题 2:

这也是简体中文网页,如何在输出时保留原文?

问题 3:

在每个表格的右上角,有一个下拉菜单可以选择合适的时期,分别是:“全部”“全年”、< strong>“半年”、“一季度”“三季度”urllib 是否能够更改此下拉菜单?

非常感谢。

最佳答案

根据该网站,所有四个表都有类名称“tab05”。

因此,您只需将 soup 中的 .find 方法更改为 .findAll,然后所有四个表可以访问。

import urllib
from bs4 import BeautifulSoup

url = 'http://stock.finance.sina.com.cn/hkstock/finance/00759.html'
html = urllib.urlopen(url).read()
soup = BeautifulSoup(html, "lxml")

tables = soup.findAll("table", { "class" : "tab05" })
print len(tables) #4

for table in tables:
for row in table.findAll("tr"):
for col in row.findAll("td"):
print col.getText()

关于简体中文的编码,print col.getText() 会在终端得到正确的单词。如果您要将它们写入文件,则必须将字符串编码为 gb2312。

f.write(col.getText().encode('gb2312'))

对于第3个问题,由于数据是通过datatable.js中写的javascript函数渲染的,我认为仅仅通过urllib是不可能全部获取到的。最好查看其他一些库以找到合适的用法。

关于python - 如何用Python选择网页的特定表格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34431833/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com