python3爬取新闻网站的所有新闻-新手起步

该篇文章适用于新手,让大家在刚接触爬虫的时候少踩点坑。作者接触python也有几个月时间了,最近要用python做数据采集的工作,因此要用爬虫去爬取各大门户网站。

好了,废话不多说,直接切入正题。

(声明:我整个工作都是在 windows下进行的。)

1.环境配置。

python就够了,关于windows下环境搭建,网上教程很多。

这里我附一个。(http://www.cnblogs.com/windinsky/archive/2012/09/20/2695520.html)

python环境确定搭建成功,就可以开始写程序去爬虫了。

2.要明确你所要爬取的网站结构。
(1)url

爬虫,实际上就是解析页面的url, 以及每个页面的标签元素(html那些)。因此,要先对你所要爬取的页面 url和内容的布局非常了解。

比如,我爬取的是凤凰网的所有新闻。 凤凰网上,大部分新闻正文的页面链接,都是这种形式,ifeng前面是新闻的分类,http://news.ifeng.com/a/20170623/51308599_0.shtml。

找到了规律,就可以用正则表达式把这些页面提取出来。

关于正则表达式的学习,网上也有很多教程。这里给大家附一个比较好的链接 http://www.jb51.net/article/57150.htm
(2)页面中的标签元素
我要提取的是新闻的标题和正文内容。 如前面所说,我找到了我想要的新闻页面,可以在浏览器里用F12, 来观察页面布局。
比如凤凰网新闻正文页面, 标题都在<div id='artical'>是<h1>标签, 正文都在<div id='main_content'>里, 是<p>标签。

3.写程序,调试运行。
这里用到了python的urllib, Beautifulsoup包。
我用的是python3, 3和2会有一些语法上的区别, 但是大体逻辑是一样的。
urllib负责对url的处理,主要是request, parse, error, 这几个模块。 负责对url发送请求,获取页面信息,error的处理。

Beautifulsoup负责对页面的解析,获取的页面是html树形结构, 通过findAll(), select(), get(), get_text()等函数即可很方便的获取到我们想要的内容。


4.最后,如果是想要获取整个门户网站的数据,则需要一些递归, 整个网站相当于一个图结构, dfs(深度优先遍历)是比较好的方法。

关于爬虫程序的书写,比较烦人的几点:

(1)不同页面url各不相同,越是大的门户网站,类别越多,总会有一些没看到,没考虑到的情况,有时候程序里判断不全面,就会报错; 相近的还有,页面标签,有些新闻正文页面布局也不太一样,用一个提取方法也就难以提取出来。 对于以上问题, 我们需要在程序里多写一些情况处理 if error,防止在爬取的时候报错 终止;

(2)编码问题, 这是我遇到最多,最棘手的问题尤其在爬虫的时候。 我是要抓取新闻,然后保存到txt中。可能有些页面会存在极个别特殊的字符,无法编码解码,经常导致程序意外终止。解决方法:对极个别难以处理的网站,在源头就把它筛选掉,抓取数据时,往往不在乎一两个页面的数据。

别人跟我说,python爬虫的特点是:简单,暴力,跟python语言风格一样。

#coding: utf-8

import codecs
from urllib import request, parse
from bs4 import BeautifulSoup
import re
import time
from urllib.error import HTTPError, URLError
import sys

###新闻类定义
class News(object):
	def __init__(self):
		self.url = None  #该新闻对应的url
		self.topic = None #新闻标题
		self.date = None #新闻发布日期
		self.content = None  #新闻的正文内容
		self.author = None  #新闻作者

###如果url符合解析要求,则对该页面进行信息提取
def getNews(url):
	#获取页面所有元素
	html = request.urlopen(url).read().decode('utf-8', 'ignore')
	#解析
	soup = BeautifulSoup(html, 'html.parser')

	#获取信息
	if not(soup.find('div', {'id':'artical'})): return 
	
	news = News()  #建立新闻对象

	page = soup.find('div', {'id':'artical'})
	
	if not(page.find('h1', {'id':'artical_topic'})): return
	topic = page.find('h1', {'id':'artical_topic'}).get_text()  #新闻标题 
	news.topic = topic

	if not(page.find('div', {'id': 'main_content'})): return 
	main_content = page.find('div', {'id': 'main_content'})   #新闻正文内容
	
	content = ''
	
	for p in main_content.select('p'):
		content = content + p.get_text()

	news.content = content

	news.url = url       #新闻页面对应的url
	f.write(news.topic+'\t'+news.content+'\n')

##dfs算法遍历全站###
def dfs(url):
	global count
	print(url)

	pattern1 = 'http://news\.ifeng\.com\/[a-z0-9_\/\.]*$'     #可以继续访问的url规则
	pattern2 = 'http://news\.ifeng\.com\/a\/[0-9]{8}\/[0-9]{8}\_0\.shtml$'  #解析新闻信息的url规则

	#该url访问过,则直接返回
	if url in visited:  return
	print(url)

	#把该url添加进visited()
	visited.add(url)
	# print(visited)

	try:
		#该url没有访问过的话,则继续解析操作
		html = request.urlopen(url).read().decode('utf-8', 'ignore')
		# print(html)
		soup = BeautifulSoup(html, 'html.parser')

		if re.match(pattern2, url):  
			getNews(url)
			# count += 1

		####提取该页面其中所有的url####
		links = soup.findAll('a', href=re.compile(pattern1))
		for link in links:
			print(link['href'])
			if link['href'] not in visited: 
				dfs(link['href'])
				# count += 1
	except URLError as e:
		print(e)
		return
	except HTTPError as e:
		print(e)
		return
	# print(count)
	# if count > 3: return

visited = set()  ##存储访问过的url

f = open('ifeng/news.txt', 'a+', encoding='utf-8')

dfs('http://news.ifeng.com/')
  • 10
    点赞
  • 60
    收藏
    觉得还不错? 一键收藏
  • 6
    评论
好的,这里提供一个简单的爬取猎聘大数据岗位相关信息的Python代码,具体步骤如下: 1. 导入所需库:requests、bs4、pandas 2. 定义一个函数,用于爬取指定面的数据,并将数据转换为DataFrame格式 3. 定义一个循环语句,用于爬取多个面的数据 4. 将所有爬取到的数据合并为一个DataFrame,并保存为Excel文件 代码如下: ```python import requests from bs4 import BeautifulSoup import pandas as pd # 定义一个函数,用于爬取指定面的数据,并将数据转换为DataFrame格式 def get_data(url): headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'} response = requests.get(url, headers=headers) soup = BeautifulSoup(response.content, 'lxml') job_list = soup.find_all('div', class_='job-info') data = [] for job in job_list: job_title = job.find('h3').text.strip() company = job.find('p', class_='company-name').text.strip() salary = job.find('span', class_='text-warning').text.strip() location = job.find('p', class_='area').text.strip() experience = job.find('p', class_='experience').text.strip() education = job.find('p', class_='education').text.strip() job_desc = job.find('p', class_='temptation').text.strip() data.append([job_title, company, salary, location, experience, education, job_desc]) df = pd.DataFrame(data, columns=['职位名称', '公司名称', '薪资', '工作地点', '工作经验', '教育程度', '职位描述']) return df # 定义一个循环语句,用于爬取多个面的数据 result = pd.DataFrame() for i in range(1, 11): url = 'https://www.liepin.com/zhaopin/?key=大数据&d_sfrom=search_fp&headckid=8cfa3a6d7e4f2f4d&flushckid=1&d_pageSize=40&d_curPage={}'.format(i) df = get_data(url) result = pd.concat([result, df], ignore_index=True) # 将所有爬取到的数据合并为一个DataFrame,并保存为Excel文件 result.to_excel('大数据岗位.xlsx', index=False) print('数据已保存!') ``` 其中,for循环语句中的range(1, 11)表示爬取10数据,可以根据需要进行修改。另外,最后一行代码将所有爬取到的数据保存为Excel文件,文件名为“大数据岗位.xlsx”,可以根据需要进行修改。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值