使用beauthoulsoup提取<br>后的文本

2024-09-24 22:26:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一系列的网页,我想从中刮出的文本都遵循不同的模式不幸。我试图编写一个scraper,它提取<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('...')

虽然这个脚本适用于某些页面,但只为其他页面获取部分或全部文本。这几天来我一直在为这件事焦头烂额,所以任何帮助都将不胜感激。在

另外,我已经尝试了this technique,但无法使其适用于所有页面。在


Tags: textorg文本brhttp网页htmlwww
1条回答
网友
1楼 · 发布于 2024-09-24 22:26:58

我仍将继续依赖span元素的underline样式。下面是一个示例代码,可以帮助您入门(使用^{}):

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())

相关问题 更多 >