爬虫——爬取网页数据存入表格

博主因个人需要自学爬虫,目标网址为http://mzj.beijing.gov.cn。设置表格编码为utf - 8,添加sheet并写入表头。用requests访问网页,BeautifulSoup解析,去除空格和空行提取有效字段,最后用insert、pop、append调整数据,还提到不同网页爬取方法或有差异。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

最近由于个人需要,从相关书籍以及网上资料进行爬虫自学,目标网址为http://mzj.beijing.gov.cn,对其内容进行整理筛选,存入excel格式。

首先是对表格的内容进行设置,编码格式定义为utf-8,添加一个sheet的表格,其中head为表头的内容,定义之后,利用sheet.write将表头内容写入。

book = xlwt.Workbook(encoding='utf-8')
sheet = book.add_sheet('ke_qq')
head = ['组织名称','登记证号','统一社会信用代码','业务主管单位','登记管理机关','社会组织类型','开办资金','业务范围','法定代表人','电话','地址','邮编','登记状态','成立日期','行业分类']#表头
for h in range(len(head)):
    sheet.write(0,h,head[h])    #写入表头

 爬取网页采用requests进行访问,利用BeautifulSoup进行解析。

response = requests.get(url, headers=headers)
soup = BeautifulSoup(response.text, 'html.parser', from_encoding='utf-8')

之后提取网页内容中有效字段,使用soup.stripped_strings去除其中的空格和空行内容。

str1 = []
    nice = []
    for wz in soup.stripped_strings:
        str1.append(repr(wz))
    k = len(str1)

最后,根据每个人不同的需要,对数据进行整理,在这里是使用insert、pop、append对数据进行一些调整。

完整代码如下:

# coding:utf-8
import requests
from bs4 import BeautifulSoup
import operator as op
import re
import xlwt

user_agent = 'Mozilla/4.0 (compatible;MSIE5.5;windows NT)'
headers = {'User-Agent': user_agent}
num=1
book = xlwt.Workbook(encoding='utf-8')
sheet = book.add_sheet('ke_qq')
head = ['组织名称','登记证号','统一社会信用代码','业务主管单位','登记管理机关','社会组织类型','开办资金','业务范围','法定代表人','电话','地址','邮编','登记状态','成立日期','行业分类']#表头
for h in range(len(head)):
    sheet.write(0,h,head[h])    #写入表头
for one in range(10001,17000):
    keyword = 10000000001
    keywords=keyword+one
    url = 'http://mzj.beijing.gov.cn/wssbweb/wssb/dc/orgInfo.do?action=seeParticular&orgId=0000' + str(keywords) + '&websitId=&netTypeId='
    response = requests.get(url, headers=headers)
    soup = BeautifulSoup(response.text, 'html.parser', from_encoding='utf-8')
    str1 = []
    nice = []
    for wz in soup.stripped_strings:
        str1.append(repr(wz))
    k = len(str1)
    if k>5:
        i = 1
        for content in str1:
            if i > 3:
                nice.append(content)
            i = i + 1
        try:
            # num=num+1
            if  op.eq(nice[4], '\'业务主管单位:\''):
                nice.insert(4, '无')
            if op.eq(nice[14], '\'法定代表人/负责人:\''):
                nice.insert(14, '无')
            if op.eq(nice[13], '\'活动地域:\''):
                nice.pop(13)
                nice.pop(13)
            if op.eq(nice[16], '\'电话:\''):
                nice.insert(16, '无')
            if op.eq(nice[18], '\'地址:\''):
                nice.insert(18, '无')
            if op.eq(nice[20], '\'邮编:\''):
                nice.insert(20, '无')
            if len(nice)>22:
                if op.eq(nice[22], '\'登记状态:\''):
                    nice.insert(22, '无')
            if len(nice) > 27:
                if op.eq(nice[27], '\'行业分类:\'') and len(nice) == 28:
                    nice.append('无')
                # if op.eq(nice[13], '\'活动地域:\''):
                #   nice.pop(13)
                #  nice.pop(13)
            if op.eq(nice[12], '\'元\''):
                nice[12] = '0'
            # print(nice)
            j = 0
            d = 0
            s = 0
            for data in nice:
                if j & 1 == 0:
                    s = j - d
                    sheet.write(num, s, data)
                    d += 1
                j += 1
            print(num)
            num += 1
        except:
            print('error'+num)

book.save('E:\WU\pyfile\shuju\save2\shuju2.xls')

其中网页地址中的keyword由于爬取网页的不同,可能采取方法有异。

### 抓取天气数据存入数据库 为了完成这一目标,程序需要分为几个部分来实现:首先是获取网页内容;其次是解析这些内容以提取所需的数据;最后是将所获得的数据存储到数据库中。 #### 获取网页内容 对于获取网页内容而言,`requests`库是一个非常方便的选择。它允许发送HTTP请求,并能轻松处理响应。下面是一段用于发起GET请求并接收服务器返回页面内容的代码: ```python import requests def get_html_text(url): try: r = requests.get(url, timeout=30) r.raise_for_status() r.encoding = 'utf-8' return r.text except Exception as e: print(f"Error occurred while fetching the URL {url}: ", str(e)) return None ``` 这段代码定义了一个名为 `get_html_text()` 的函数,该函数接受一个URL作为参数,并尝试访问此网址以获取其HTML文本[^2]。 #### 解析网页内容 一旦有了网页的HTML文档,就可以利用像BeautifulSoup这样的工具对其进行解析。这一步骤旨在定位和抽取特定标签内的信息——在这个例子中即为天气预报详情。以下是具体做法: ```python from bs4 import BeautifulSoup def parse_weather_data(html): soup = BeautifulSoup(html, "html.parser") weather_list = [] # 假设每条记录都位于<tr>标签内 trs = soup.find_all('tr') for tr in trs[1:]: # 跳过表头行 tds = tr.find_all('td') city = tds[0].string.strip() date = tds[1].string.strip() high_temp = int(tds[2].string.strip()) low_temp = int(tds[3].string.strip()) item = { 'city': city, 'date': date, 'high_temperature': high_temp, 'low_temperature': low_temp } weather_list.append(item) return weather_list ``` 上述代码片段展示了如何创建一个新的列表`weather_list[]`用来保存每一项天气预测的具体情况。这里假设表格结构是以<code><tr></code>标记表示一行,而城市名、日期以及高低温分别由不同的<td>单元格承载。 #### 存储至MySQL数据库 当准备好要储存的数据之后,下一步就是建立与MySQL之间的连接,并执行相应的SQL命令向其中写入新纪录。为此需要用到PyMySQL模块,它可以让我们很方便地操作关系型数据库。下面是关于怎样设置这种链接及其后续动作的例子: ```python import pymysql def save_to_mysql(weather_items): conn = pymysql.connect( host='localhost', user='root', password='password', database='weatherdb' ) cursor = conn.cursor() sql_create_table = """ CREATE TABLE IF NOT EXISTS daily_weather ( id INT AUTO_INCREMENT PRIMARY KEY, city VARCHAR(50), date DATE, high_temperature INT, low_temperature INT ); """ cursor.execute(sql_create_table) insert_sql = """INSERT INTO daily_weather (city, date, high_temperature, low_temperature) VALUES (%s,%s,%s,%s);""" for item in weather_items: cursor.execute(insert_sql, [ item['city'], item['date'], item['high_temperature'], item['low_temperature'] ]) conn.commit() cursor.close() conn.close() ``` 以上脚本首先建立了同本地运行着的一个实例化后的MySQL服务端口相匹配的新会话(`conn`)对象,接着构建了一张新的表单(如果不存在的话),最终遍历之前收集起来的所有天气项目并通过预编译过的语句逐个插入进去[^1]。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值