Python urllibライブラリとBeautifulSoupライブラリを使用した爬虫類のまとめ


最近は爬虫類を簡単に勉強したので、ちょっとしたまとめをして、批判して指摘してください.
Python爬虫類まとめ
インストールに成功したかどうかを確認
  • python
  • python

  • urllib
  • from urllib.request import urlopen

  • BeautifulSoup4
  • from bs4 import BeautifulSoup


  • MySQLへのデータの保存
  • pipでpymysqlをインストールする
  • pip install pymysql

  • インストールファイル
  • python set.py install


  • 備考:ソースコード(github-master)->解凍->Cmd->cdをsetupにダウンロードします.pyフォルダの下->このフォルダを実行します
    リアルブラウザのシミュレーション
  • User-Agentヘッダを携帯
  • req = request.Request(url)
  • req.add_header(key,value)
  • resp = request.urlopen(req)
  • print(resp.read().decode(“utf_8”))


  • POSTの使用
  • urllibライブラリの下にあるparseをインポート
  • from urllib import parse

  • urlencodeを使用してpostデータを生成
  • postData = parse.urlencode([ (key1,val1), (key2,val2), (keyn,valn)

  • postDataを使用してpostリクエストを送信
  • request.urlopen(req,data = postData.encode(“utf-8”))

  • 取得要求状態
  • resp.status

  • 取得サーバのタイプ
  • resp.reason


  • MySQLへのデータの保存
  • 開発パッケージの導入
  • import pymysql.cursors

  • データベース・リンクの取得
  • connection = pymysql.connect(host = “localhost”, user =’root’, password = ‘123456’, db = ‘wikiurl’, charset = ‘utf8mb4’)

  • 提出
  • connection.commit()

  • クローズ
  • connection.close()


  • MySQLデータの読み込み
  • 取得総記録数
  • cursor.excute()

  • 次の行を問い合わせる
  • cursor.fechone()

  • 指定されたサイズを取得
  • cursor.fetchall()
  • cursor.fetchmany(size=None)

  • クローズ
  • connection.close()


  • 一般的なドキュメントの読み込み
  • TXTドキュメントの読み込み
  • urlopen()

  • pdfドキュメントの読み取り
  • pdfminer3k


  • コードブロック
    from urllib.request import urlopen
    from urllib.request import Request
    from urllib import parse
    from bs4 import BeautifulSoup
    
    url = "http://baidu.com"
    req = Request(url)
    postData = parse.urlencode([
        ("StartStation" , "#####"),
        ("EndStation","#####"),
        ("####","####"),
        ]
        )
    
    req.add.header("User_Agent","Mozilla/5.0(Windows NT 10.0,WOW64) AppleWebKit/537.36(KHT)")
    
    resp = urlopen(req,data= postData.encode("utf-8"))
    
    #  BeautifulSoup   
    soup = BeautifulSoup(resp,'html.parser')
    
    #     /wiki/   a   href  
    listUrls = soup.findAll("a",href = re.compile("^/wiki/"))
    
    #             URL
    for url in listUrls:
        #  .jpg/.JPG   URL
        if not re.search("\.(jpg|JPG)$",url["href"]):
            #  URL         
            #string      get_text()          
            print(url.get.text(),","https://en.wikipedia.org"+url["href"])
    #print(resp.read().decode("utf-8"))
    
    #       
    connection = pymysql.connect(host = "localhost",
                    user = "root",
                    password = "123456",
                    db = "\wikiurl",
                    charset = "utf8mb4")
    try :
        #      
        with connection.cursor() as cursor:
            #  sql  
            sql = "insert into `urls`(`urlname`,`urlhref`) values (%s,%s)"
            #  sql  
            cursor.excute(sql,(url.get.text(),"https://en.wikipedia.org"+url["href"]))
            #  
            connection.commit()
    finally:
        connection.close()

    データ領域
    Beautiful Soup 4.2.0公式文書