Pythonはデータベースに爬虫類PyQueryのシンプルなライブラリと情報をクロール

まずヘッド最初のインポートライブラリ:

import os
import requests
from pyquery import PyQuery as pq
import pymysql # 用于连接并操作MySQL数据库

各サイトのUser-Agent、例えば、事前にユーザーエージェントを探すためにウェブサイトを開く必要のために異なるヘッドの導入は、私はウェブサイト上の情報をクロールされます。https://www.icourse163.org/university/view/all.htm# /赤丸の部分を見つける、ネットワークをクリックして、ビューとFirefoxのオープン要素を右クリック
ここに画像を挿入説明して、コードを挿入します。

headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3423.2 Safari/537.36'
}

そして、応答で要求を送信するために主にある検索機能を、書きます。

def search():
    url = 'https://www.icourse163.org/university/view/all.htm#/'
    try:
        response = requests.get(url, headers=headers)
        if response.status_code == 200:
            return response.text
    except requests.ConnectionError:
        return None

必要な情報を取得する書き込み位置は次のとおりです。

def get_image(html):
    doc = pq(html)
    items = doc('.g-flow .u-usitys .u-usity ').items()  # 如果不加.items(),items就不是pyquery对象

    for item in items:
        yield {
            'title': item.find('img').attr('alt'),
            'image': item.find('img').attr('src')
        }

:小さなパートナーは、適切な情報を右クリックし、Firefoxでサイトを開き、このような情報の場所を見つける方法を知っている要素を表示しませんがあるかもしれません
ここに画像を挿入説明
そして、画像を保存する機能を記述します。

def save_image(item):
    file_path_all = 'D:/python-pro/partners'#存储图片的本地地址
    if not os.path.exists(file_path_all):
        os.makedirs(file_path_all)
    try:
        response = requests.get(item.get('image'))
        if response.status_code == 200:
            file_path = '{0}/{1}.{2}'.format(file_path_all, item.get('title'), 'jpg')  # 以图片名字命名的话,可能会有重复的,造成图片丢失          
            if not os.path.exists(file_path):
                with open(file_path, 'wb') as f:
                    f.write(response.content)
            else:
                print('Already Download', file_path)
    except requests.ConnectionError:
        print('Failed to Save Image')

最後に、主な機能を記述します。

def main():
    connection = pymysql.connect(host='localhost',  # 连接数据库
                                 user='root',
                                 password='',  # 你安装mysql时设置的密码
                                 db='test2',
                                 charset='utf8',
                                 cursorclass=pymysql.cursors.DictCursor)
    sql = "insert into partners(name,url,parId)values(%s,%s,%s)"
    try:
        html = search()
        cursor = connection.cursor()
        i = 1
        for item in get_image(html):

            print([i]+[item])
            save_image(item)
            cursor.execute(sql, (item['title'], item['image'], i))
            connection.commit()
            i += 1

    finally:
        connection.close()
        return None


if __name__ == '__main__':
    main()

:結果は以下のとおりである
ここに画像を挿入説明地元の絵に:
ここに画像を挿入説明データベース内に格納されたデータを:
ここに画像を挿入説明
最後にすべてのコードを添付します:

import os
import requests
from pyquery import PyQuery as pq
import pymysql # 用于连接并操作MySQL数据库

headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3423.2 Safari/537.36'
}

def search():
    url = 'https://www.icourse163.org/university/view/all.htm#/'
    try:
        response = requests.get(url, headers=headers)
        if response.status_code == 200:
            return response.text
    except requests.ConnectionError:
        return None

def get_image(html):
    doc = pq(html)
    items = doc('.g-flow .u-usitys .u-usity ').items()  # 如果不加.items(),items就不是pyquery对象

    for item in items:
        yield {
            'title': item.find('img').attr('alt'),
            'image': item.find('img').attr('src')
        }

def save_image(item):
    file_path_all = 'D:/python-pro/partners'#存储图片的本地地址
    if not os.path.exists(file_path_all):
        os.makedirs(file_path_all)
    try:
        response = requests.get(item.get('image'))
        if response.status_code == 200:
            file_path = '{0}/{1}.{2}'.format(file_path_all, item.get('title'), 'jpg')  # 以图片名字命名的话,可能会有重复的,造成图片丢失
            if not os.path.exists(file_path):
                with open(file_path, 'wb') as f:
                    f.write(response.content)
            else:
                print('Already Download', file_path)
    except requests.ConnectionError:
        print('Failed to Save Image')

def main():
    connection = pymysql.connect(host='localhost',  # 连接数据库
                                 user='root',
                                 password='',  # 你安装mysql时设置的密码
                                 db='test2',
                                 charset='utf8',
                                 cursorclass=pymysql.cursors.DictCursor)
    sql = "insert into partners(name,url,parId)values(%s,%s,%s)"
    try:
        html = search()
        cursor = connection.cursor()
        i = 1
        for item in get_image(html):

            print([i]+[item])
            save_image(item)
            cursor.execute(sql, (item['title'], item['image'], i))
            connection.commit()
            i += 1

    finally:
        connection.close()
        return None


if __name__ == '__main__':
    main()

注意事項

  1. コードは、データベースサーバー名に、独自のデータベース名を接続するために変更しなければならない、または接続が上にありません。
  2. 事前pyqueryライブラリ、Pythonのデフォルトでインストールされていない、手動でインストールする必要があります。
  3. 適切なクロールクラス名の情報を確認し、エラーになります。
  4. このコードは、学習のためのものです。
リリース5元の記事 ウォンの賞賛5 ビュー325

おすすめ

転載: blog.csdn.net/weixin_42848583/article/details/104346218