簡體   English   中英

之后提取文本 <br> 與BeautifulSoup

[英]Extracting texts after <br> with BeautifulSoup

我有一系列的網頁,我想從中抓取所有不幸的是遵循不同模式的文本。 我正在嘗試編寫一個刮板,該刮板在<br>標記后提取文本,因為該結構對所有頁面都是通用的。

這些頁面盡我所能遵循三種基本模式:

  1. http://www.p2016.org/ads1/bushad120215.html
  2. http://www.p2016.org/ads1/christiead100515.html
  3. http://www.p2016.org/ads1/patakiad041615.html

現在,我正在抓取以下循環:

  for br in soup.find_all('br'):
        text = br.next_sibling

        try:         
            print text.strip().replace("\t", " ").replace("\r", " ").replace('\n', ' ')
        except AttributeError:
            print('...')

雖然此腳本適用於某些頁面,但僅獲取某些文本或不獲取其他文本。 最近幾天,我一直在為此扯頭發,所以任何幫助將不勝感激。

另外,我已經嘗試過這種技術 ,但是無法使它適用於所有頁面。

我仍將繼續依靠span元素的underline樣式。 這是一個示例代碼,可以幫助您入門(使用.next_siblings ):

for span in soup.select('p > span[style*=underline]'):
    texts = []
    for sibling in span.next_siblings:
        # break upon reaching the next span 
        if sibling.name == "span":
            break

        text = sibling.get_text(strip=True) if isinstance(sibling, Tag) else sibling.strip()
        if text:
            texts.append(text.replace("\n", " "))

    if texts:
        text = " ".join(texts)
        print(span.text.strip(), text.strip())

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM