【问题标题】:Python: BeautifulSoup Findall Skip to the Next TagPython: BeautifulSoup Findall 跳到下一个标签
【发布时间】:2013-11-12 01:07:56
【问题描述】:

我正在使用以下代码写入 csv 文件。

import urllib2
from BeautifulSoup import BeautifulSoup
import csv
import re

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

f = csv.writer(open("pe_ratio.csv","wb"))
f.writerow(["Name","PE","Revenue % YOY","ROA% YOY","OCF Positive","Debt - Equity"])

soup = BeautifulSoup(page)
all_data = soup.findAll('td', "yfnc_tabledata1")
f.writerow(('Ford', all_data[2].getText()))



name_company = soup.findAll("div", {"class" : "title"})
# find all h2

#print soup.prettify

#h2 div class="title"

print name_company

我找到了要放入 csv 文件的内容,但现在我需要将其限制为“Ford Motor Co. (F)。当我将 name_company 打印出来时,我得到了这个:

 [<div class="title"><h2>Ford Motor Co. (F)</h2>     <span class="rtq_exch">    <span             class="rtq_dash">-</span>NYSE      </span><span class="wl_sign"></span></div>]

我尝试过使用 name_company.next 和 name_company.content[0]。什么会起作用? name_company 使用 findall,我不知道这是否会使 .content 和 .next 为空。提前感谢您的帮助。

【问题讨论】:

    标签: python csv beautifulsoup findall


    【解决方案1】:

    使用find() 获取下一个&lt;h2&gt; 标签并使用string 读取其文本节点。

    name_company = soup.findAll("div", {"class" : "title"})
    for name in name_company:
        print name.find('h2').string
    

    更新:参见 cmets。

    for name in name_company:
        ford = name.find('h2').string
        f.writerow([ford, all_data[2].getText()])
    

    它产生:

    Name,PE,Revenue % YOY,ROA% YOY,OCF Positive,Debt - Equity
    Ford Motor Co. (F),11.23
    

    【讨论】:

    • 谢谢。在这行代码中,我将如何编写打印的内容来替换“福特”? f.writerow(('福特', all_data[2].getText()))
    最近更新 更多