python爬虫爬取Bloomberg新闻

2023-10-08 19:30

本文主要是介绍python爬虫爬取Bloomberg新闻,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

最近在爬取bloomberg上的新闻,所以在这里记录一下过程。

思路

通过网站的sitemap获取链接,解析链接通过scrapy框架爬取。


网站链接的获取:

https://www.bloomberg.com/robots.txt 这是网站的robots.txt,如下:
# Bot rules:
# 1. A bot may not injure a human being or, through inaction, allow a human being to come to harm.
# 2. A bot must obey orders given it by human beings except where such orders would conflict with the First Law.
# 3. A bot must protect its own existence as long as such protection does not conflict with the First or Second Law.
# If you can read this then you should apply here https://www.bloomberg.com/careers/
User-agent: *
Disallow: /news/live-blog/2016-03-11/bank-of-japan-monetary-policy-decision-and-kuroda-s-briefing
Disallow: /polska
User-agent: Mediapartners-Google*
Disallow: /about/careers
Disallow: /about/careers/
Disallow: /offlinemessage/
Disallow: /apps/fbk
Disallow: /bb/newsarchive/
Disallow: /apps/news
Sitemap: https://www.bloomberg.com/feeds/bbiz/sitemap_index.xml
Sitemap: https://www.bloomberg.com/feeds/bpol/sitemap_index.xml
Sitemap: https://www.bloomberg.com/feeds/bview/sitemap_index.xml
Sitemap: https://www.bloomberg.com/feeds/gadfly/sitemap_index.xml
Sitemap: https://www.bloomberg.com/feeds/quicktake/sitemap_index.xml
Sitemap: https://www.bloomberg.com/bcom/sitemaps/people-index.xml
Sitemap: https://www.bloomberg.com/bcom/sitemaps/private-companies-index.xml
Sitemap: https://www.bloomberg.com/feeds/bbiz/sitemap_securities_index.xml
User-agent: Spinn3r
Disallow: /podcasts/
Disallow: /feed/podcast/
Disallow: /bb/avfile/
User-agent: Googlebot-News
Disallow: /sponsor/
Disallow: /news/sponsors/*

其中红色部分是我们要爬取的sitemap,打开其中一个,会有如下的xml文件:
<sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
<sitemap>
<loc>
https://www.bloomberg.com/feeds/gadfly/sitemap_recent.xml
</loc>
<lastmod>2017-02-17T07:46:07-05:00</lastmod>
</sitemap>
<sitemap>
<loc>
https://www.bloomberg.com/feeds/gadfly/sitemap_news.xml
</loc>
<lastmod>2017-02-17T07:46:07-05:00</lastmod>
</sitemap>
<sitemap>
<loc>
https://www.bloomberg.com/feeds/gadfly/sitemap_2017_2.xml
</loc>
<lastmod>2017-02-17T07:46:07-05:00</lastmod>
</sitemap>



我们需要提取其中的<loc>*</loc>中的内容,这仍然是sitemap,打开后如下:

<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:news="http://www.google.com/schemas/sitemap-news/0.9" xmlns:image="http://www.google.com/schemas/sitemap-image/1.1">
<url>
<loc>
https://www.bloomberg.com/gadfly/articles/2017-02-17/luxury-tax
</loc>
<news:news>
<news:publication>
<news:name>Bloomberg</news:name>
<news:language>en</news:language>
</news:publication>
<news:title>Giving U.S. Border Tax a European Luxury Snub</news:title>
<news:publication_date>2017-02-17T10:43:15.284Z</news:publication_date>
<news:keywords>
Sales Tax, Jobs, China, Europe, Ralph Lauren, Michael David Kors, Bernard Arnault, Donald John Trump, Miuccia Prada Bianchi
</news:keywords>
<news:stock_tickers>LON:BRBY, EPA:MC, LON:BARC, EPA:KER</news:stock_tickers>
</news:news>
<image:image>
<image:loc>
https://assets.bwbx.io/images/users/iqjWHBFdfxIU/iurmUVIRXTqY/v0/1200x-1.jpg
</image:loc>
<image:license>https://www.bloomberg.com/tos</image:license>
</image:image>
</url>


<loc>标签中的内容就是我们需要爬取的新闻地址。

第一步,要获得所有的新闻地址,代码如下:

# -*- coding: utf-8 -*-
#可以下载网站的sitemap
import re
from downloader import Downloader #downloader的作用是下载网页内容
D = Downloader()file1 = open('sitemaps.txt','a')
file2 = open('htmls.txt','a')
def crawl_sitemap(url):#download sitemap filesitemap = D(url)#extract the sitemap linkslinks = re.findall('<loc>(.*?)</loc>',sitemap)#download each linkfor link in links:file1.write(link)file1.write('\n')html = D(link)file2.write(html)file2.write('\n')
crawl_sitemap('https://www.bloomberg.com/feeds/gadfly/sitemap_index.xml')#上面四个红色的sitemap,这里就放了一个,没有写到一起。file1.close()
file2.close()

downloader文件:
import urlparse
import urllib2
import random
import time
from datetime import datetime, timedelta
import socketDEFAULT_AGENT = 'wswp'
DEFAULT_DELAY = 5
DEFAULT_RETRIES = 1
DEFAULT_TIMEOUT = 60class Downloader:def __init__(self, delay=DEFAULT_DELAY, user_agent=DEFAULT_AGENT, proxies=None, num_retries=DEFAULT_RETRIES,timeout=DEFAULT_TIMEOUT, opener=None, cache=None):socket.setdefaulttimeout(timeout)self.throttle = Throttle(delay)self.user_agent = user_agentself.proxies = proxiesself.num_retries = num_retriesself.opener = openerself.cache = cachedef __call__(self, url):result = Noneif self.cache:try:result = self.cache[url]except KeyError:# url is not available in cachepasselse:if self.num_retries > 0 and 500 <= result['code'] < 600:# server error so ignore result from cache and re-downloadresult = Noneif result is None:# result was not loaded from cache so still need to downloadself.throttle.wait(url)proxy = random.choice(self.proxies) if self.proxies else Noneheaders = {'User-agent': self.user_agent}result = self.download(url, headers, proxy=proxy, num_retries=self.num_retries)if self.cache:# save result to cacheself.cache[url] = resultreturn result['html']def download(self, url, headers, proxy, num_retries, data=None):print 'Downloading:', urlrequest = urllib2.Request(url, data, headers or {})opener = self.opener or urllib2.build_opener()if proxy:proxy_params = {urlparse.urlparse(url).scheme: proxy}opener.add_handler(urllib2.ProxyHandler(proxy_params))try:response = opener.open(request)html = response.read()code = response.codeexcept Exception as e:print 'Download error:', str(e)html = ''if hasattr(e, 'code'):code = e.codeif num_retries > 0 and 500 <= code < 600:# retry 5XX HTTP errorsreturn self._get(url, headers, proxy, num_retries - 1, data)else:code = Nonereturn {'html': html, 'code': code}def _get(self, url, headers, proxy, param, data):passclass Throttle:"""Throttle downloading by sleeping between requests to same domain"""def __init__(self, delay):# amount of delay between downloads for each domainself.delay = delay# timestamp of when a domain was last accessedself.domains = {}def wait(self, url):"""Delay if have accessed this domain recently"""domain = urlparse.urlsplit(url).netloclast_accessed = self.domains.get(domain)if self.delay > 0 and last_accessed is not None:sleep_secs = self.delay - (datetime.now() - last_accessed).secondsif sleep_secs > 0:time.sleep(sleep_secs)self.domains[domain] = datetime.now()
通过以上的代码,我们得到了对应sitemap下的xml文件


然后提取其中的<loc> </loc>标签的内容:
import re
file = open('./sitemap_and_html_waiting_to_be_crawled/htmls_gadfly.txt')
file2 = open('htmls.txt','a')for temp in file.readlines():if re.match('<loc>',temp.strip()) is None:passelse:print temp#file2.write(temp)#file2.write('\n')
file.close()
file2.close()

得到的文件中还会有<loc>标签,直接用文本编辑去掉就行,最后的文件形式是这样的:


另外的几个sitemap改一下上面第一段代码中的地址就行了。这样就获取了全部的新闻地址,接下来开始爬取新闻内容。

——————————————割——————————————————————————————————————————————————————————————

scrapy爬虫

爬虫教程:https://doc.scrapy.org/en/1.3/intro/tutorial.html
这里需要一些安装,都很容易,打开cmd在一个目录下输入:
scrapy startproject linkcrawler
这样就创建了一个scrapy爬虫,在spiders目录下,创建爬虫文件,写入代码:
import scrapy
file = open('G:\onedrive\workspace\crawler\htmls\htmls_gadfly.txt')#这里是之前html文件的地址
data = file.readlines()def list_to_string(list):string = ""for i in list:string += i.strip()return stringclass LinkCrawler(scrapy.Spider):name = "link"def start_requests(self):"""urls = ['https://www.bloomberg.com/gadfly/articles/2017-02-16/baidu-failing-fast-is-a-smart-move-to-build-a-future','https://www.bloomberg.com/gadfly/articles/2017-02-13/gaslog-partners-poised-for-lng-market-recovery','https://www.bloomberg.com/gadfly/articles/2017-02-07/bp-earnings-today-doesn-t-match-tomorrow']:return:"""for url in data:yield scrapy.Request(url=url, callback=self.parse)def parse(self, response): #这里是比较关键的部分,主要用了css选择器,选择需要的部分,下面会详细讲yield{'title': response.css('h1.headline_4rK3h>a::text').extract_first(),'time_1': response.css("time::text").extract_first().strip(),'time_2': response.css('time').re(r'datetime="\s*(.*)">')[0],'content': list_to_string(response.css('div.container_1KxJx>p::text').extract())}file.close()

这就是全部代码了,很easy啊。
还是刚才的cmd窗口,输入
scrapy crawl link -o news.json
 经过一段时间的运行,就把所有的新闻保存在一个news.json文件中了。


css选择器:

我们得到网页链接之后最重要的就是分析网页内容,选择我们想要的内容,这部分其实很多方法,包括正则表达式,beautifulsoup,lxml,我们直接用scrapy自带的css选择器进行选择。
随意打开一个网页,首先是标题:如下所示


我们关注的部分是:

在命令行中打开scrapy shell:、

后面是网址。
在scrapy shell中输入
response.css('h1.headline_4rK3h>a::text').extract_first()
可以看到标题就提取出来了。
还有一点就是爬取bloomberg的时候一定要能上Google,最好是全局代理,不然是连不上的。

总结

原理很简单就是通过网站的sitemap进行爬取,代码写的有点罗嗦,不过功能是实现了,可以比较稳定快速的爬取bloomberg的新闻,第一次发博客,希望如果有大神看到能指点一二。

这篇关于python爬虫爬取Bloomberg新闻的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/167530

相关文章

Python函数作用域示例详解

《Python函数作用域示例详解》本文介绍了Python中的LEGB作用域规则,详细解析了变量查找的四个层级,通过具体代码示例,展示了各层级的变量访问规则和特性,对python函数作用域相关知识感兴趣... 目录一、LEGB 规则二、作用域实例2.1 局部作用域(Local)2.2 闭包作用域(Enclos

Python实现对阿里云OSS对象存储的操作详解

《Python实现对阿里云OSS对象存储的操作详解》这篇文章主要为大家详细介绍了Python实现对阿里云OSS对象存储的操作相关知识,包括连接,上传,下载,列举等功能,感兴趣的小伙伴可以了解下... 目录一、直接使用代码二、详细使用1. 环境准备2. 初始化配置3. bucket配置创建4. 文件上传到os

使用Python实现可恢复式多线程下载器

《使用Python实现可恢复式多线程下载器》在数字时代,大文件下载已成为日常操作,本文将手把手教你用Python打造专业级下载器,实现断点续传,多线程加速,速度限制等功能,感兴趣的小伙伴可以了解下... 目录一、智能续传:从崩溃边缘抢救进度二、多线程加速:榨干网络带宽三、速度控制:做网络的好邻居四、终端交互

Python中注释使用方法举例详解

《Python中注释使用方法举例详解》在Python编程语言中注释是必不可少的一部分,它有助于提高代码的可读性和维护性,:本文主要介绍Python中注释使用方法的相关资料,需要的朋友可以参考下... 目录一、前言二、什么是注释?示例:三、单行注释语法:以 China编程# 开头,后面的内容为注释内容示例:示例:四

Python中win32包的安装及常见用途介绍

《Python中win32包的安装及常见用途介绍》在Windows环境下,PythonWin32模块通常随Python安装包一起安装,:本文主要介绍Python中win32包的安装及常见用途的相关... 目录前言主要组件安装方法常见用途1. 操作Windows注册表2. 操作Windows服务3. 窗口操作

Python中re模块结合正则表达式的实际应用案例

《Python中re模块结合正则表达式的实际应用案例》Python中的re模块是用于处理正则表达式的强大工具,正则表达式是一种用来匹配字符串的模式,它可以在文本中搜索和匹配特定的字符串模式,这篇文章主... 目录前言re模块常用函数一、查看文本中是否包含 A 或 B 字符串二、替换多个关键词为统一格式三、提

python常用的正则表达式及作用

《python常用的正则表达式及作用》正则表达式是处理字符串的强大工具,Python通过re模块提供正则表达式支持,本文给大家介绍python常用的正则表达式及作用详解,感兴趣的朋友跟随小编一起看看吧... 目录python常用正则表达式及作用基本匹配模式常用正则表达式示例常用量词边界匹配分组和捕获常用re

python实现对数据公钥加密与私钥解密

《python实现对数据公钥加密与私钥解密》这篇文章主要为大家详细介绍了如何使用python实现对数据公钥加密与私钥解密,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 目录公钥私钥的生成使用公钥加密使用私钥解密公钥私钥的生成这一部分,使用python生成公钥与私钥,然后保存在两个文

python删除xml中的w:ascii属性的步骤

《python删除xml中的w:ascii属性的步骤》使用xml.etree.ElementTree删除WordXML中w:ascii属性,需注册命名空间并定位rFonts元素,通过del操作删除属... 可以使用python的XML.etree.ElementTree模块通过以下步骤删除XML中的w:as

使用Python绘制3D堆叠条形图全解析

《使用Python绘制3D堆叠条形图全解析》在数据可视化的工具箱里,3D图表总能带来眼前一亮的效果,本文就来和大家聊聊如何使用Python实现绘制3D堆叠条形图,感兴趣的小伙伴可以了解下... 目录为什么选择 3D 堆叠条形图代码实现:从数据到 3D 世界的搭建核心代码逐行解析细节优化应用场景:3D 堆叠图