python静态网页爬虫实例01

前些日子学习了一些爬虫知识,鉴于时间较短,就只看了静态网页爬虫内容,而有关scrapy爬虫框架将在后续继续探索。

以下以重庆市统计局官网某页面爬取为例(http://tjj.cq.gov.cn/tjsj/sjjd/201608/t20160829_434744.htm):

0、程序代码

 1 import requests
 2 from bs4 import BeautifulSoup
 3
 4 headers = {‘user-agent‘: ‘Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.146 Safari/537.36‘}
 5 url = ‘http://tjj.cq.gov.cn/tjsj/sjjd/201608/t20160829_434744.htm‘
 6 res = requests.get(url, headers=headers)
 7 res.encoding = res.apparent_encoding
 8 soup = BeautifulSoup(res.text, ‘html.parser‘)
 9 trs = soup.find_all(‘table‘)[2].find_all(‘tr‘)
10 # print(trs)
11 data = []
12 for tr in trs:
13     info = []
14     tds = tr.find_all(‘td‘)
15     if(len(tds) ==5 ):
16         for td in tds:
17             info.append(td.text.replace(‘\u3000‘, ‘‘))
18         print(info)
19     else:
20         continue
21     data.append(info)

1、准备工作

1.1  打开所给的url,我们发现该网页包含三个表,选取第三个表作为提取对象。

1.2  观察网页源代码,发现该表包含在<table>……<table/>里面,表中每一行包含在<tr>……</tr>里,而该行的每一列又被包含在<td>……<td/> 里。

2、获取网址请求

2.1  首先导入requests库和美丽的汤——BeautifulSoup库

1 import requests
2 from bs4 import BeautifulSoup

2.2  利用requests库中的requests.get()方法以及相关属性完成网址请求

1 headers = {‘user-agent‘: ‘Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.146 Safari/537.36‘}
2 url = ‘http://tjj.cq.gov.cn/tjsj/sjjd/201608/t20160829_434744.htm‘
3 res = requests.get(url, headers=headers)
4 res.encoding = res.apparent_encoding

3、网页解析

之前准备工作中,已经对网页源代码有了一定的分析。接下来,直接利用BeautifulSoup库完成网页解析。

 1 soup = BeautifulSoup(res.text, ‘html.parser‘)
 2 trs = soup.find_all(‘table‘)[2].find_all(‘tr‘)
 3 # print(trs)
 4 data = []
 5 for tr in trs:
 6     info = []
 7     tds = tr.find_all(‘td‘)
 8     if(len(tds) ==5 ):
 9         for td in tds:
10             info.append(td.text.replace(‘\u3000‘, ‘‘))
11         print(info)
12     else:
13         continue

4、代码优化

利用pandas库可以将提取数据并形成Excel表格输出,优化后的代码如下:

 1 # -*- coding: utf-8 -*-
 2
 3 import requests
 4 from bs4 import BeautifulSoup
 5 import pandas as pd
 6
 7 class CQstat(object):
 8     def __init__(self):
 9         self.headers = {
10                 ‘User-Agent‘:‘Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.120 Safari/537.36‘
11                 }
12
13     def get_html(self,url):
14         try:
15             r = requests.get(url,headers=self.headers)
16             r.raise_for_status()
17             r.encoding = r.apparent_encoding
18             return r.text
19         except:
20             return None
21
22     def get_info(self):
23         url = ‘http://tjj.cq.gov.cn/tjsj/sjjd/201608/t20160829_434744.htm‘
24         html = self.get_html(url)
25         soup = BeautifulSoup(html,‘lxml‘)
26         trs = soup.find_all(‘table‘)[2].find_all(‘tr‘)
27         data = []
28         for tr in trs:
29             info = []
30             tds = tr.find_all(‘td‘)
31             if len(tds) == 3:
32                 for td in tds:
33                     info.append(td.text.replace(‘\u3000‘,‘‘))
34                 info.insert(2,‘主营业务收入‘)
35                 info.append(‘利润总额‘)
36             elif len(tds) == 4:
37                 for td in tds:
38                     info.append(td.text.replace(‘\u3000‘,‘‘))
39                 info.insert(0,‘行业‘)
40             elif len(tds) == 5:
41                 for td in tds:
42                     info.append(td.text.replace(‘\u3000‘,‘‘))
43             else:
44                 continue
45             data.append(info)
46         df = pd.DataFrame(data)
47         df.to_excel(‘1-7月份规模以上工业企业主要财务指标(分行业).xlsx‘,index=None,header=None)
48
49 cq = CQstat()
50 cq.get_info()

原文地址:https://www.cnblogs.com/chenmenghu/p/12268274.html

时间: 2024-07-30 03:48:01

python静态网页爬虫实例01的相关文章

Python静态网页爬虫相关知识

想要开发一个简单的Python爬虫案例,并在Python3以上的环境下运行,那么需要掌握哪些知识才能完成一个简单的Python爬虫呢? 爬虫的架构实现 爬虫包括调度器,管理器,解析器,下载器和输出器.调度器可以理解为主函数的入口作为整个爬虫的头部,管理器实现包括对URL是否重复进行 判断,将已经爬到的URL加入到列表防止重复爬取.解析器则是对网页内容进行解析,解析出新的URL和网页内容.下载器则是下载解析器解析出的URL.输 出器则是顾名思义. 1.1 调度器 我的理解为类似主函数的入口,可以启

python静态网页爬虫之xpath

常用语句: 1.starts-with(@属性名称,属性字符相同部分)使用情形: 以相同的字符开头 <div id = 'test-1'>需要的内容1</div> <div id = 'test-2'>需要的内容2</div> <div id = 'test-3'>需要的内容3</div> selector = etree.HTML(html) content = selector.xpath('//div[start-with(@i

Python编写网页爬虫爬取oj上的代码信息

OJ升级,代码可能会丢失. 所以要事先备份. 一开始傻傻的复制粘贴, 后来实在不能忍, 得益于大潇的启发和聪神的原始代码, 网页爬虫走起! 已经有段时间没看Python, 这次网页爬虫的原始代码是 python2.7版本, 试了一下修改到3.0版本, 要做很多包的更替,感觉比较烦,所以索性就在这个2.7版本上完善了. 首先观赏一下原始代码,我给加了一些注释: # -*- coding: cp936 -*- import urllib2 import urllib import re import

【爬虫】如何用python+selenium网页爬虫

一.前提 爬虫网页(只是演示,切勿频繁请求):https://www.kaola.com/ 需要的知识:Python,selenium 库,PyQuery 参考网站:https://selenium-python-zh.readthedocs.io/en/latest/waits.html 二.简单的分析下网站 三.步骤 1.目标: 1.open brower 2.open url from selenium import webdriver from selenium.common.excep

Python静态网页爬取:批量获取高清壁纸

前言 在设计爬虫项目的时候,首先要在脑内明确人工浏览页面获得图片时的步骤 一般地,我们去网上批量打开壁纸的时候一般操作如下: 1.打开壁纸网页 2.单击壁纸图(打开指定壁纸的页面) 3.选择分辨率(我们要下载高清的图) 4.保存图片 实际操作时,我们实现了如下几步网页地址的访问:打开了壁纸的网页→单击壁纸图打开指定页面→选择分辨率,点击后打开最终保存目标图片网页→保存图片 在爬虫的过程中我们就尝试通过模拟浏览器打开网页的操作,一步步获得.访问网页.最后获得目标图片的下载地址,对图片进行下载保存到

python之路——爬虫实例

urlController.py import bsController from urllib import request class SpiderMain(object): def __init__(self): self.header = {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11', 'Ac

Python简单网页爬虫

由于Python2.x与Python3.x存在很的差异,Python2.x调用urllib用指令urllib.urlopen(), 运行时报错:AttributeError: module 'urllib' has no attribute 'urlopen' 原因是在Python3.X中应该用urllib.request. 下载网页成功后,调用webbrowsser模块,输入指令webbrowsser .open_new_tab('baidu.com.html') true open('bai

Python学习---网页爬虫[下载图片]

爬虫学习--下载图片 1.主要用到了urllib和re库 2.利用urllib.urlopen()函数获得页面源代码 3.利用正则匹配图片类型,当然正则越准确,下载的越多 4.利用urllib.urlretrieve()下载图片,并且可以重新命名,利用%S 5.应该是运营商有所限制,所以未能下载全部的图片,不过还是OK的 URL分析: 源码: #coding=utf-8 import re import urllib def getHtml(url): page=urllib.urlopen(u

Python 简单网页爬虫

网上的妹子图爬虫:只爬取一个人物相册 import requests from bs4 import BeautifulSoup headers = { 'User-Agent':'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)', 'Referer':'http://www.mzitu.com' } # 初始链接 start_url = 'https://www.mzitu.com/161470' start_html = requests