python爬蟲入門之————————————————第二節--使用xpath語法獲取數據

準備工作

⚫瞭解爬蟲的數據處理體系結構

⚫ 處理數據的軟件準備 採集到的結構化數據[如 html 網頁文檔數據] python 開發環境 lxml 第三方庫 結構化數據基本理論:DOM 模型 

1結構化數據

具備有一定的結構,有預定義規則的數據模型,統稱爲結構化數據 如:數據進行格式化展示的 HTML 文檔中的數據、數據進行格式化傳輸的 XML 文檔中的數據、數據進行格式化整理的 Excel 表格中的數據等等都是結構 化數據;同時按照表中行和列的形式進行數據整理的數據庫中的數據,也是結構化數據 
因爲結構化數據有預定義規則的數據模型,所以可以被按照路徑進行解析 爬蟲採集的大都是網絡上的網頁數據,就常見的兩種數據格式進行分析【html 網頁文檔數據、xml 數據文檔】 

2.xlml下載安裝

官方網站:https://lxml.de/ 
下載安裝:pypi 下載地址 https://pypi.org/project/lxml/#files 下載對應的 wheel 包,通過命令的方式直接安裝即可

pip install lxml-4.2.5-cp36-cp36m-win32.whl

注意:下載離線包時切記注意安裝依賴關係[依賴的python 平臺版本和操作系統平臺] 
命令安裝方式:  打開 windows 的命令行 or unix/linux 的 shell 窗口  通過包管理命令安裝:pip install lxml 

招聘網站的信息爬取

案例演示:

"""
Version 1.1.0
Author lkk
Email [email protected]
date 2018-11-20 15:38
DESC 招聘網站信息爬取
"""
from urllib import request

from fake_useragent import UserAgent
import chardet,pymysql
from lxml import etree


# 定義請求頭
def getinfo():
    ua = UserAgent()
    headers = {
        'User-agent': ua.random
    }
    url_list = [
        'http://sydw.huatu.com/ha/zhaopin/1.html',
        'http://sydw.huatu.com/ha/zhaopin/2.html',
        'http://sydw.huatu.com/ha/zhaopin/3.html',
        'http://sydw.huatu.com/ha/zhaopin/4.html',
        'http://sydw.huatu.com/ha/zhaopin/5.html',
        'http://sydw.huatu.com/ha/zhaopin/6.html',
        'http://sydw.huatu.com/ha/zhaopin/7.html',
        'http://sydw.huatu.com/ha/zhaopin/8.html',
        'http://sydw.huatu.com/ha/zhaopin/9.html',
        'http://sydw.huatu.com/ha/zhaopin/10.html',
                ]
    for j in url_list:
        start_url = request.Request(j, headers=headers)
        response = request.urlopen(start_url)
        content = response.read()
        encoding = chardet.detect(content).get('encoding')
        content = content.decode(encoding, 'ignore')
        # print(content)
        # 通過xpath直接提取其中的某個指定數據
        docs = etree.HTML(content)
        times = docs.xpath("//ul[@class='listSty01']/li/time/text()")
        city = docs.xpath("//ul[@class='listSty01']/li/lm/a/text()")
        info = docs.xpath("//ul[@class='listSty01']/li/a/text()")
        for i in range(len(times)):
            print(times[i], city[i], info[i])
            mysql(times[i], city[i], info[i])


class DownMysql:
    def __init__(self, times, city, info):
        self.times = times
        self.city = city
        self.info = info
        self.connect = pymysql.connect(
            host='localhost',
            db='data',
            port=3306,
            user='root',
            passwd='123456',
            charset='utf8',
            use_unicode=False
        )
        self.cursor = self.connect.cursor()

    # 保存數據到MySQL中
    def save_mysql(self):
        sql = "insert into invite(times, city, info) VALUES (%s,%s,%s)"
        try:
            self.cursor.execute(sql, (self.times, self.city, self.info))
            self.connect.commit()
            print('數據插入成功')
        except Exception as e:
            print(e)


# 新建對象,然後將數據傳入類中
def mysql(times, city, info):
    down = DownMysql(times, city, info)
    down.save_mysql()


if __name__ == '__main__':
    getinfo()

3.lxml-xpath常見的基本操作


 
 電影天堂的爬取

import requests, chardet
from lxml import html
from fake_useragent import UserAgent

ua = UserAgent()
headers = {'User-agent': ua.random, 'cookie': None}
response = requests.get('http://www.dy2018.com', headers=headers)

content = response.content
encoding = chardet.detect(content).get('encoding')
content = content.decode(encoding, 'ignore')

docs = html.fromstring(content)
links = docs.xpath("//div[@class='co_content222']/ul/li/a")
for link in links:     
    print(link.xpath('string(.)').strip())

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章