Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/windows/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 使用BeautifulSoup设置限制_Python_Beautifulsoup_Limit - Fatal编程技术网

Python 使用BeautifulSoup设置限制

Python 使用BeautifulSoup设置限制,python,beautifulsoup,limit,Python,Beautifulsoup,Limit,我正在使用以下代码从NATI中提取PE比率,我已经阅读了crummy的文档,并且“几乎”了解nextSibling、.content和以前的兄弟(我怀疑它们与XML和DOM有关)。我仍在试图弄清楚,因为我认为从长远来看,使用该代码将比下面的代码更漂亮。我想知道的是,是否可以设置一个限制范围…即。2:3(仅搜索2到3) 我使用以下代码,得到了以下结果: PS C:\python27\stock_program> python pe_ratio.py [<td class="yfnc_t

我正在使用以下代码从NATI中提取PE比率,我已经阅读了crummy的文档,并且“几乎”了解nextSibling、.content和以前的兄弟(我怀疑它们与XML和DOM有关)。我仍在试图弄清楚,因为我认为从长远来看,使用该代码将比下面的代码更漂亮。我想知道的是,是否可以设置一个限制范围…即。2:3(仅搜索2到3)

我使用以下代码,得到了以下结果:

PS C:\python27\stock_program> python pe_ratio.py
[<td class="yfnc_tabledata1"><span id="yfs_j10_nati">3.80B</span></td>, <td    class="yfnc_tabledata1">3.48B</td>, <td clas
s="yfnc_tabledata1">49.15</td>]
并展示:

49.15
提前感谢您的帮助和建议

python2.x

import urllib2
from BeautifulSoup import BeautifulSoup

page = urllib2.urlopen('http://finance.yahoo.com/q/ks?s=NATI%20Key%20Statistics').read()

soup = BeautifulSoup(page)

all_data = soup.findAll('td', "yfnc_tabledata1")

print all_data[2].getText()

# or - for more elements

for element in all_data[0:3]:
    print element.getText()

# write to CSV

import csv

with open("results.csv", "wb") as f:
    writer = csv.writer(f)

    writer.writerow(["header1", "header2", "header3"])  

    for element in all_data[0:3]:
        writer.writerow([element.getText(), "column2", "column3"])
结果:

47.65
# or - for more elements
3.69B
3.38B
47.65
CSV文件:

header1,header2,header3
3.69B,column2,column3
3.38B,column2,column3
47.65,column2,column3

如果我理解正确,你只想要第二和第三个结果?您可以将限制设置为3并忽略第一个结果。我希望最终将其写入CSV文件。
导入CSV
-请参阅(尤其是页面底部的示例)我在下面的回答中添加了CSV示例。
47.65
# or - for more elements
3.69B
3.38B
47.65
header1,header2,header3
3.69B,column2,column3
3.38B,column2,column3
47.65,column2,column3