【问题标题】:Extracting texts after <br> with BeautifulSoup使用 BeautifulSoup 提取 <br> 之后的文本
【发布时间】:2016-03-28 02:45:11
【问题描述】:

不幸的是,我有一系列网页想要从中抓取文本,它们都遵循不同的模式。我正在尝试编写一个在&lt;br&gt; 标签之后提取文本的刮板,因为该结构对所有页面都是通用的。

据我所知,这些页面遵循三种基本模式:

  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,但无法使其适用于所有页面。

【问题讨论】:


  • 标签实际上没有“中间”,因为没有打开和关闭。我想你的意思是“之后”,对吧?
  • 对不起,是的。我将编辑问题。

标签: python html regex web-scraping bs4


【解决方案1】:

我仍然会继续依赖 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())

【讨论】:

  • 我越是搞砸这个,就越觉得你是对的。我得到的输出是多个字符串,而不仅仅是一个适合 csv 单元格的字符串。我的输出脚本错了吗? with open('p2016ads.csv', 'wb') as csvoutput: writer = csv.writer(csvoutput, delimiter=';', quoting=csv.QUOTE_ALL, quotechar="|") writer.writerow(["group", "text", "details","link"]) rows = zip(org,txt,deets, link) for row in rows: writer.writerow(row)
猜你喜欢
  • 1970-01-01
  • 2011-07-13
  • 2022-11-19
  • 1970-01-01
  • 1970-01-01
  • 2023-03-16
  • 2015-03-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多