【问题标题】:Locating specific <p> tag after <h1> tag in Python Html Parser在 Python Html Parser 中的 <h1> 标记之后定位特定的 <p> 标记
【发布时间】:2013-11-15 18:29:08
【问题描述】:

我正在尝试解析一系列网页,并在每个页面上出现标题后仅抓取 3 个段落。它们都有相同的格式(我认为)。我正在使用 urllib2 和漂亮的汤,但我不太确定如何跳转到标题然后抓住几个

跟随它的标签。我知道第一个 split("h1") 不正确,但这是我迄今为止唯一一次体面的尝试。这是我的代码,

from bs4 import BeautifulSoup
import urllib2
from HTMLParser import HTMLParser

BANNED = ["/events/new"]

def main():

    soup = BeautifulSoup(urllib2.urlopen('http://b-line.binghamton.edu').read())

     for link in soup.find_all('a'):
         link = link.get('href')      
        if link != None and link not in BANNED and "/events/" in link:
            print()
            print(link)          
            eventPage = "http://b-line.binghamton.edu" + link
            bLineSubPage = urllib2.urlopen(eventPage)   
            bLineSubPageStr = bLineSubPage.read()
            headAccum = 0  
            for data in bLineSubPageStr.split("<h1>"):
                if(headAccum < 1):
                    accum = 0 
                    for subData in data.split("<p>"):
                        if(accum < 5):
                            try:
                                print(BeautifulSoup(subData).get_text())
                            except Exception as e:
                                print(e) 
                            accum+=1
                    print()
                headAccum += 1           
            bLineSubPage.close()         
            print()

main()

【问题讨论】:

    标签: python parsing html-parsing beautifulsoup urllib2


    【解决方案1】:
    >>> page_txt = urllib2.urlopen("http://b-line.binghamton.edu/events/9305").read(
    >>> soup = bs4.BeautifulSoup(pg.split("<h1>",1)[-1])
    >>> print soup.find_all("p")[:3]
    

    这就是你想要的吗?

    【讨论】:

    • 这完全有效。谢谢你。我没有意识到你可以像这样索引汤数据。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-26
    • 2020-07-26
    • 1970-01-01
    • 1970-01-01
    • 2017-03-18
    相关资源
    最近更新 更多