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编写一个git自动上传的脚本(打包成exe)

《基于Python编写一个git自动上传的脚本(打包成exe)》这篇文章主要为大家详细介绍了如何基于Python编写一个git自动上传的脚本并打包成exe,文中的示例代码讲解详细,感兴趣的小伙伴可以跟... 目录前言效果如下源码实现利用pyinstaller打包成exe利用ResourceHacker修改e

Python在二进制文件中进行数据搜索的实战指南

《Python在二进制文件中进行数据搜索的实战指南》在二进制文件中搜索特定数据是编程中常见的任务,尤其在日志分析、程序调试和二进制数据处理中尤为重要,下面我们就来看看如何使用Python实现这一功能吧... 目录简介1. 二进制文件搜索概述2. python二进制模式文件读取(rb)2.1 二进制模式与文本

Python中Tkinter GUI编程详细教程

《Python中TkinterGUI编程详细教程》Tkinter作为Python编程语言中构建GUI的一个重要组件,其教程对于任何希望将Python应用到实际编程中的开发者来说都是宝贵的资源,这篇文... 目录前言1. Tkinter 简介2. 第一个 Tkinter 程序3. 窗口和基础组件3.1 创建窗

Django调用外部Python程序的完整项目实战

《Django调用外部Python程序的完整项目实战》Django是一个强大的PythonWeb框架,它的设计理念简洁优雅,:本文主要介绍Django调用外部Python程序的完整项目实战,文中通... 目录一、为什么 Django 需要调用外部 python 程序二、三种常见的调用方式方式 1:直接 im

Python字符串处理方法超全攻略

《Python字符串处理方法超全攻略》字符串可以看作多个字符的按照先后顺序组合,相当于就是序列结构,意味着可以对它进行遍历、切片,:本文主要介绍Python字符串处理方法的相关资料,文中通过代码介... 目录一、基础知识:字符串的“不可变”特性与创建方式二、常用操作:80%场景的“万能工具箱”三、格式化方法

浅析python如何去掉字符串中最后一个字符

《浅析python如何去掉字符串中最后一个字符》在Python中,字符串是不可变对象,因此无法直接修改原字符串,但可以通过生成新字符串的方式去掉最后一个字符,本文整理了三种高效方法,希望对大家有所帮助... 目录方法1:切片操作(最推荐)方法2:长度计算索引方法3:拼接剩余字符(不推荐,仅作演示)关键注意事

python版本切换工具pyenv的安装及用法

《python版本切换工具pyenv的安装及用法》Pyenv是管理Python版本的最佳工具之一,特别适合开发者和需要切换多个Python版本的用户,:本文主要介绍python版本切换工具pyen... 目录Pyenv 是什么?安装 Pyenv(MACOS)使用 Homebrew:配置 shell(zsh

Python自动化提取多个Word文档的文本

《Python自动化提取多个Word文档的文本》在日常工作和学习中,我们经常需要处理大量的Word文档,本文将深入探讨如何利用Python批量提取Word文档中的文本内容,帮助你解放生产力,感兴趣的小... 目录为什么需要批量提取Word文档文本批量提取Word文本的核心技术与工具安装 Spire.Doc

Python中Request的安装以及简单的使用方法图文教程

《Python中Request的安装以及简单的使用方法图文教程》python里的request库经常被用于进行网络爬虫,想要学习网络爬虫的同学必须得安装request这个第三方库,:本文主要介绍P... 目录1.Requests 安装cmd 窗口安装为pycharm安装在pycharm设置中为项目安装req

Python容器转换与共有函数举例详解

《Python容器转换与共有函数举例详解》Python容器是Python编程语言中非常基础且重要的概念,它们提供了数据的存储和组织方式,下面:本文主要介绍Python容器转换与共有函数的相关资料,... 目录python容器转换与共有函数详解一、容器类型概览二、容器类型转换1. 基本容器转换2. 高级转换示