我正在尝试编写一个程序来读取任何可能包含Blogspot或Wordpress博客/任何其他网站的网站的文章(帖子)。至于编写与几乎所有可能用HTML5 / XHTML等编写的网站兼容的代码。我想过使用RSS / Atom提要作为提取内容的基础。
然而,随着RSS / ATOM通常供稿可能不包含的网站整个的文章,我想用feedparser
,然后要提取相应的URL文章内容收集从进料全部“上岗”的链接。
我能得到的所有文章的网址在网站(包括总结。即,在饲料中显示文章内容),但我想访问整个文章的数据,我必须使用相应的URL。
我在各个图书馆来了,如同BeautifulSoup
,lxml
等。(不同的HTML / XML解析器),但我真的不知道如何让文章的“精确”的内容(我假设“精确”表示所有超链接,iframe,幻灯片等数据仍然存在;我不想要CSS部分。)
那么,任何人都可以帮助我吗?
答案 0 :(得分:3)
获取所有链接页面的HTML代码非常简单。
困难的部分是准确提取您要查找的内容。如果您只需要<body>
标记内的所有代码,那么这也不是一个大问题;提取所有文本同样简单。但是如果你想要一个更具体的子集,你还有更多工作要做。
我建议你下载请求和BeautifulSoup模块(可以通过easy_install requests/bs4
或更好pip install requests/bs4
获得)。请求模块使得获取页面非常容易。
以下示例提取rss feed并返回三个列表:
linksoups
是从Feed链接的每个页面的 BeautifulSoup 实例列表linktexts
是从Feed linkimageurls
是包含src
的列表列表 - 从Feed中链接的每个页面中嵌入的所有图片的网址
[['/pageone/img1.jpg', '/pageone/img2.png'], ['/pagetwo/img1.gif', 'logo.bmp']]
import requests, bs4
# request the content of the feed an create a BeautifulSoup object from its content
response = requests.get('http://rss.slashdot.org/Slashdot/slashdot')
responsesoup = bs4.BeautifulSoup(response.text)
linksoups = []
linktexts = []
linkimageurls = []
# iterate over all <link>…</link> tags and fill three lists: one with the soups of the
# linked pages, one with all their visible text and one with the urls of all embedded
# images
for link in responsesoup.find_all('link'):
url = link.text
linkresponse = requests.get(url) # add support for relative urls with urlparse
soup = bs4.BeautifulSoup(linkresponse.text)
linksoups.append(soup)
linktexts.append(soup.find('body').text)
# Append all text between tags inside of the body tag to the second list
images = soup.find_all('img')
imageurls = []
# get the src attribute of each <img> tag and append it to imageurls
for image in images:
imageurls.append(image['src'])
linkimageurls.append(imageurls)
# now somehow merge the retrieved information.
这可能是您项目的一个粗略起点。