【问题标题】:How do I extract just the blog content and exclude other elements using Beautiful Soup如何使用 Beautiful Soup 仅提取博客内容并排除其他元素
【发布时间】:2018-01-31 03:03:27
【问题描述】:

我正在尝试从blog post 获取博客内容,我的意思是前六段。到目前为止,这是我想出的:

soup = BeautifulSoup(url, 'lxml')
body = soup.find('div', class_='post-body')

打印body 还会在主 div 标签下包含其他内容。

【问题讨论】:

    标签: python python-3.x web-scraping beautifulsoup


    【解决方案1】:

    试试这个:

    import requests ; from bs4 import BeautifulSoup
    
    res = requests.get("http://www.fashionpulis.com/2017/08/being-proud-too-soon.html").text
    soup = BeautifulSoup(res, 'html.parser')
    for item in soup.select("div#post-body-604825342214355274"):
        print(item.text.strip())
    

    使用这个:

    import requests ; from bs4 import BeautifulSoup
    
    res = requests.get("http://www.fashionpulis.com/2017/08/acceptance-is-must.html").text
    soup = BeautifulSoup(res, 'html.parser')
    for item in soup.select("div[id^='post-body-']"):
        print(item.text)
    

    【讨论】:

    • 谢谢!但是,我想知道是否有一种方法可以将刮板重新用于类似的博客文章。例如,this one from the same site 的 id 不同但格式相似。
    • 那么,post-body id 每次都要硬编码?
    • 另一种方式是import re; soup.findAll('div', class_=re.compile('post-body'))。 BeautifulSoup 原生处理
    • @Bargain23,您是否尝试过第二个脚本中的两个网址?它也可以从两个站点中获取内容。谢谢。
    【解决方案2】:

    我发现这个解决方案非常有趣:Scrape multiple pages with BeautifulSoup and Python

    但是,我还没有找到任何要处理的查询字符串参数,也许你可以从这种方法开始。

    我觉得现在最明显的事情是这样的:

    1. 每月和每年都从页面的博客存档部分获取所有标题(例如,http://www.fashionpulis.com/2017/03/ 等)
    2. 使用标题和相应的月​​份/年份构建 URL(URL 始终为 http://www.fashionpulis.com/$YEAR/$MONTH/$TITLE.html)
    3. 按照 Shahin 在上一个答案中的描述刮掉文本

    【讨论】:

      猜你喜欢
      • 2011-01-09
      • 2019-07-15
      • 2020-05-04
      • 2017-12-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-04
      • 1970-01-01
      相关资源
      最近更新 更多