int*_*ong -1 python beautifulsoup web-scraping
我在上个月左右一直在学习python的基础知识,虽然我非常擅长打印'hello world',但我想学习一些额外的功能.我已下载BeautifulSoup4并使用Python2.7.我的目标是能够从CNN或其他新闻来源获取文章并能够废弃4件事:1)链接到网站2)发布日期文章3)文章标题4)文章文本
我已经在stackoverflow中搜索了其他问题并查看了其他示例代码,但是我将它应用于我想要做的事情时遇到了问题.我看到的大多数例子都是在刮擦时间或天气.我的主要问题是,当我查看特定网站的源代码时,我很难知道我应该使用哪些标签.
例如,如果我想废弃以上4件事:http: //www.cnn.com/2013/10/29/us/florida-shooting-cell-phone-blocks-bullet/index.html?http = ju_c2
代码会是什么样的?
这是一个概念代码的证明,让你的想法工作,只是为了让你知道,BeautifulSoup4真的很强大,它绝对足够你的第一阶段刮.
您还需要阅读CNN的服务条款,以确定是否允许抓取.您可以在BS4文档中找到以下代码的每个细节的解释,或者您可以在stackoverflow中开始您的职业生涯,以了解社区的每个细节,就像我所做的那样:)祝您好运并享受它!
from bs4 import BeautifulSoup, SoupStrainer
import urllib2
import re
def main():
opener = urllib2.build_opener()
opener.addheaders = [('User-agent', 'Mozilla/5.0')]
url = 'http://www.cnn.com/2013/10/29/us/florida-shooting-cell-phone-blocks-bullet/index.html?hpt=ju_c2'
soup = BeautifulSoup(opener.open(url))
#1) Link to the website
#2) Date article published
date = soup.find("div", {"class":"cnn_strytmstmp"}).text.encode('utf-8')
#3) title of article
title = soup.find("div", {"id":"cnnContentContainer"}).find('h1').text.encode('utf-8')
#4) Text of the article
paragraphs = soup.find('div', {"class":"cnn_strycntntlft"}).find_all('p')
text = " ".join([ paragraph.text.encode('utf-8') for paragraph in paragraphs])
print url
print date
print title
print text
if __name__ == '__main__':
main()
Run Code Online (Sandbox Code Playgroud)
输出如下所示:
http://www.cnn.com/2013/10/29/us/florida-shooting-cell-phone-blocks-bullet/index.html?hpt=ju_c2
updated 7:34 AM EDT, Tue October 29, 2013
Cell phone stops bullet aimed at Florida gas station clerk
(CNN) -- A gas station clerk's smartphone may... the TV station reported.
Run Code Online (Sandbox Code Playgroud)
同时,关于我们应该如何定位元素的一些哲学:链接在这里. 和Selenium/Scrapy你可能也会在以后遇到..