使用BeautifulSoup从一个博客归档页面中提取多个帖子,无需脚本

2024-10-03 00:23:41 发布

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

我试图从一系列WordPress和Blogger博客存档页面中获取作者、标题、日期和帖子内容。我已经把页面保存下来了,这样就不会重复ping服务器了。我已经完成了其他部分的工作,但我似乎不能同时从每个文件中获取所有的帖子,也不能从底部获得“add to any”或“socialible”或其他凌乱的脚本。我在这里。在

import urllib2
from bs4 import BeautifulSoup
import re

file_list = open ("hafiles.txt", "r")
posts_file = open ("haposts.txt","w")


for indurl in file_list:
    indurl = indurl.rstrip("\n")
    with open(indurl,"r") as ha_file:
     soup_ha = BeautifulSoup(ha_file)

    #works the second find gets rid of the sociable crap
    # this is the way it looks on the page <div class='post-body'>

    posts = soup_ha.find("div", class_="post-body").find_all("p")


    #tried a trick i saw on http://stackoverflow.com/questions/24458353/cleaning-text-string-after-getting-body-text-using-beautifulsoup
    #no joy
    #posts = soup_ha.find("div", class_="post-body")
    #text = [''.join(s.findAll(text=True))for s in posts.findAll('p')] 
    text = str(posts) + "\n" + "\n"
    posts_file.write (text)

print ("All done!")



file_list.close()
posts_file.close()

所以如果我做了一个find_all并得到了所有的帖子(甚至不确定我是否真的得到了它们),那么我就得到了脚本。如果我只使用find,至少有两种方法可以不用脚本就可以得到漂亮的帖子。我有一个文件列表,每个文件有几个帖子要提取。 我已经在stackoverflow和web上搜索过了。在

在eta:输入是一个非常混乱的网页,上面有大量的脚本,所有的css定义都在页面上

^{pr2}$

恶心!所以我大概有20个左右的文件,每一个都有1到10个帖子(这有2个)。。。最可爱的是一个csv或excel文件 日期作者标题后内容

每列一行。 我将采取一个文件,只是张贴内容与一些空间之间的每一篇文章。我对文本中的一些链接和一些粗体和列表之类的都很好,但我不想要所有凌乱的脚本。 谢谢


Tags: 文件thetextimport脚本内容body页面
1条回答
网友
1楼 · 发布于 2024-10-03 00:23:41

下面是一个包含多个帖子的单页示例:

from bs4 import BeautifulSoup


soup = BeautifulSoup(open('test.html'))
posts = []
for post in soup.find_all('div', class_='post'):
    title = post.find('h3', class_='post-title').text.strip()
    author = post.find('span', class_='post-author').text.replace('Posted by', '').strip()
    content = post.find('div', class_='post-body').p.text.strip()
    date = post.find_previous_sibling('h2', class_='date-header').text.strip()

    posts.append({'title': title,
                  'author': author,
                  'content': content,
                  'date': date})
print posts

对于您发布的html,它将打印:

^{pr2}$

相关问题 更多 >