python实现基本的爬虫技术

python实现基本的爬虫技术

import csv
import urllib.error
import urllib.request

from bs4 import BeautifulSoup

# 定义基础url
baseurl = ""


# 定义一个函数getHtmlByURL,得到指定url网页的内容
def geturl(url):
    # 自定义headers(伪装以免被反爬虫)
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36'
    }
    # 创建请求对象,并设置请求方法和请求体
    req = urllib.request.Request(url, method="GET", headers=headers)
    # 定义一个接收变量,用于接收
    html = ""
    try:
        # urlopen()方法的参数,发送给服务器并接收响应
        resp = urllib.request.urlopen(req)
        # urlopen()获取页面内容,返回的数据格式为bytes类型,需要decode()解码,转换成str类型
        html = resp.read().decode("utf-8")
    except urllib.error.URLError as e:
        if hasattr(e, "code"):
            print(e.code)
        if hasattr(e, "reason"):
            print(e.reason)
    return html


# 将数据保存到CSV文件中。
def save_data_to_csv(data, csv_file_path):
    with open(csv_file_path, mode='w', newline='') as csv_file:
        writer = csv.DictWriter(csv_file, fieldnames=['title'])
        writer.writeheader()
        for row in data:
            writer.writerow(row)
        print("保存成功!")


# 定义一个函数,并解析这个网页
def analysisData(url):
    # 获取指定网页
    html = geturl(url)
    # 指定解析器解析html,得到BeautifulSoup对象
    soup = BeautifulSoup(html, "html5lib")
    temp = []
    # 统计条数
    textCount = 0
    # 下面逐级解析数据结构
    for item0 in soup.findAll('div', class_="subCont"):
        for item1 in item0.findAllNext('ul', class_="news_list2"):
            for item2 in item1.findAllNext('li'):
                for item3 in item2.findAllNext('span', class_="title"):
                    for item4 in item3.findAllNext('span'):
                        for item5 in item4.findAllNext('a'):
                            if 'title' in item5.attrs:
                                # 去掉无关信息
                                if item5['title'] not in ['于启用网上商城框架协议采购专区车辆维修保养服务品目的通知》的通知', '第一页', '最后一页', '更多页码',
                                                          '前页码 请在页面展示区点击相应的页码查询', '更多页码 请在页面展示区点击相应的页码查询']:
                                    print(item5['title'])
                                    x = {}
                                    x['title'] = item5['title']
                                    temp.append(x)
                                    textCount = textCount + 1
    print("total:", textCount)
    save_data_to_csv(temp, 'data.csv')
    return ""


def main():
    print(analysisData(baseurl + "0"))

# 点这个运行!点这个运行!点这个运行!点这个运行!
if __name__ == "__main__":
    main()

你可能感兴趣的:(python,python,爬虫,开发语言)