ページをクロールするためにはPythonを使用するために、我々は次の4つのモジュールを習得する必要があります。
パッケージ | 効果 |
---|---|
ウェブブラウザ | 指定されたページを取得し、ブラウザを開きます。 |
リクエスト | インターネットからファイルやページをダウンロードします。 |
美しいスープ | ページフォーマットでエンコードされた、すなわちHTMLを解析します。 |
セレン | 開始し、Webブラウザを制御し、フォームに必要事項を記入することができ、およびマウスクリックをシミュレートします。 |
小さなプロジェクト:ウェブブラウザモジュールを使用bilibiliSearch.py
ウェブブラウザモジュールのopen()
機能は、新しいブラウザを起動し、指定されたURLを開くことができます。
import webbrowser
webbrowser.open("https://bilibili.com")
上記のコード例を実行し、システムがB駅を開き、新しいタブを起動します。しかし、それは事を行うことができますウェブブラウザモジュールもあります。
嗶哩嗶哩を使用したり、クリップボード内の特定のテキストを検索します。我々は、機能を達成するためにしている場合。私たちのプログラムは、実行する必要があります。
- コマンドラインパラメータまたはクリップボードの内容を検索するようにして、
- 検索結果にWebブラウザ、ポイントを開きます。
嗶哩嗶哩検索指定された場所のURLアドレスを明確化
最初のBステーションが手動で「日小川鬼畜」を検索我々はとしてURL URLアドレスバーを見つけることができます:「https://search.bilibili.com/all?keyword=日小川総裁は20%鬼畜、」私たちは、限り、あなたは検索したいように、見つけることができますキーワードでコンテンツのスペースで区切って複数のキーワードに=の後に、URLにされて20%
表明しました。
コマンドライン引数を処理
検索するコマンドラインの内容からパラメータをインポートするには、我々は、SYSバッグをインポートして使用する必要がsys.argv
彼らのコンテンツを取得します。
クリップボードの内容を扱います
パッケージpyperclip使用しpyperclip.paste()
、クリップボードの内容を取得する機能を。
次のようにこのように、全体のプログラムコードは、次のとおりです。
import webbrowser, sys, pyperclip
if len(sys.argv) > 1:
# Get address from command line.
address = ' '.join(sys.argv[1:])
else:
# Get address from clipboard.
address = pyperclip.paste()
webbrowser.open("https://search.bilibili.com/all?keyword="+address)
リクエストとWebモジュールからファイルをダウンロードしてください
requests.get()
URLアドレスの文字列をダウンロードする機能を受信して作られたあなたの要求に、Webサーバーからの応答を含むResponseオブジェクトを返します。
>>> import requests
>>> res = requests.get('http://www.gutenberg.org/cache/epub/1112/pg1112.txt')
>>> type(res)
<class 'requests.models.Response'>
>>> res.status_code == requests.codes.ok
True
>>> len(res.text)
179378
>>> requests.codes.ok
200
>>> print(res.text[:300])
The Project Gutenberg EBook of Romeo and Juliet, by William Shakespeare
*******************************************************************
THIS EBOOK WAS ONE OF PROJECT GUTENBERG'S EARLY FILES PRODUCED AT A
TIME WHEN PROOFING METHODS AND TOOLS WERE NOT WELL DEVELOPED. THERE
IS AN IMPROVED
オブジェクトは属性の数、含まれているstatus_code
ステータスコードと呼ばれる、プロパティの値は、要求が成功したかどうかを確認することができ、text
プロパティは、Webページ内のテキスト情報に含まれます。ステータスコード200の成功した訪問は、一般的に、他の人が失敗していることを言及する価値があります。
失敗したアクセスしたときに我々が使用できるraise_for_status()
メソッドは例外をスローし、プログラムが停止します。私たちは例外をスローする場合は、プログラムが停止したくない、あなたが使用することができますtry
し、except
文を包みます。
>>> res = requests.get("http://www.donotexists777.com")
>>> res.status_code
404
>>> res.raise_for_status()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "D:\Anaconda3\envs\mlbook\lib\site-packages\requests\models.py", line 940, in raise_for_status
raise HTTPError(http_error_msg, response=self)
requests.exceptions.HTTPError: 404 Client Error: Not Found for url: http://miwifi.com/diagnosis/index.html
ハードドライブにダウンロードしたファイルを保存します
>>> import requests
>>> res = requests.get('http://www.gutenberg.org/cache/epub/1112/pg1112.txt')
>>> res.raise_for_status()
>>> playFile = open('RomeoAndJuliet.txt', 'wb')
>>> for chunk in res.iter_content(100000):
... playFile.write(chunk)
...
100000
79380
>>> playFile.close()
標準使用するopen()
とwrite()
、ローカルファイルへのWebページを保存する方法をバイナリでファイルを開くための方法として、ここでWB引数を使用して、私たちは内のテキスト記述することができます「Unicodeエンコーディングを。」
メモリの使用量を削減するために、我々は、使用iter_content()
地域のテキスト文書に書かれたバッチでの方法を。
BeautifulSoupモジュールは、HTMLを解析し、使用します
ポリシーのHTMLフォーマットを解析表現を使用しない理由は、HTMLフォーマットは、多くの異なる方法を持つことができ、まだ有効なHTMLとみなされるが、非常に面倒になり、これらすべての可能な変更をキャプチャするために正規表現を使用しよう、と、ということですエラーが発生しやすいです。BeautifulSoupモジュールは、欠陥の原因となることは容易ではありません。
HTML BeautifSoupからオブジェクトを作成します。
bs4.BeautifulSoup()関数呼び出しは、HTMLを解析する含む文字列を期待しています。bs4.BeautifulSoup()関数は、BeautifulSoupオブジェクトを返します。
>>> import requests, bs4
>>> res = requests.get('http://www.baidu.com')
>>> res.raise_for_status()
>>> baiduSoup = bs4.BeautifulSoup(res.text)
>>> type(baiduSoup)
<class 'bs4.BeautifulSoup'>
要素を見つけるために、select()メソッドを使用します
要素を探し、呼び出すselect()
Webページの要素を取得することができるように、CSS「セレクター」などの文字列を渡し、方法を。
<!-- This is the example.html example file. -->
<html><head><title>The Website Title</title></head>
<body>
<p>Download my <strong>Python</strong> book from <a href="http://
inventwithpython.com">my website</a>.</p>
<p class="slogan">Learn Python the easy way!</p>
<p>By <span id="author">Al Sweigart</span></p>
</body></html>
上記の例を見てみると、「example.html」として上記のコードを保存し、現在のフォルダに保存されています。
>>> from bs4 import BeautifulSoup
>>> exampleFile = open('./example.html')
>>> exampleSoup = BeautifulSoup(exampleFile.read(), features='html.parser')
>>> elems = exampleSoup.select('#author')
>>> type(elems)
<class 'list'>
>>> len(elems)
1
>>> type(elems[0])
<class 'bs4.element.Tag'>
>>> elems[0].getText()
'Al Sweigart'
>>> str(elems[0])
'<span id="author">Al Sweigart</span>'
>>> elems[0].attrs
{'id': 'author'}
小さなプロジェクト
漫画のランキングを登ります - -
私たちはその後、cmdと入力し、すべてのブラウザを閉じる必要がファンにログインする必要性のいくつかを表示するには:
"C:\Program Files (x86)\Microsoft\Edge Beta\Application\msedge.exe" --remote-debugging-port=8888
次へ:
from selenium import webdriver
import time
"""
First, run:
"C:\Program Files (x86)\Microsoft\Edge Beta\Application\msedge.exe" --remote-debugging-port=8888
in the cmd.
"""
options = webdriver.ChromeOptions()
options.debugger_address = "127.0.0.1:" + '8888'
options.binary_location = r"C:\Program Files (x86)\Microsoft\Edge Beta\Application\msedge.exe"
chrome_driver_binary = r"D:\APP\MicrosoftWebDriver.exe"
driver = webdriver.Chrome(chrome_driver_binary, chrome_options=options)
for i in range(1, 100):
url = "https://bangumi.tv/anime/tag/%E6%90%9E%E7%AC%91?page=" + str(i)
driver.get(url)
time.sleep(5) # Let the user actually see something!
filepath = str(i) + '.html'
with open(filepath, 'wb') as f:
f.write(driver.page_source.encode("utf-8", "ignore"))
print(filepath + "写入成功!")
f.close()
上記は、00ローカルにダウンロードページファイル用です
- 以下は、パースします -
from bs4 import BeautifulSoup
import re
dateRegex = re.compile(r"(\d{4})\D+(\d{1,2})\D+(\d{1,2})") # 规范化日期
with open('topAnime.txt', 'a', encoding="utf-8") as f:
for i in range(1, 77):
filepath = str(i) + '.html'
soup = BeautifulSoup(open(filepath, encoding="utf-8"), 'html.parser')
nameList = soup.find_all(name="h3")
for name in nameList:
link = "https://bangumi.tv" + name.contents[1]["href"]
f.writelines('[' + name.contents[1].string.strip('\n') + ']' + '(' + link + ')')
if len(name) >= 4:
f.writelines("\t" + name.contents[3].string.strip('\n'))
else:
f.writelines("\tNone")
for sibling in name.next_siblings:
try:
if sibling.attrs["class"] == ['info', 'tip']:
# f.writelines("\tinfo: " + sibling.string.strip())
date = dateRegex.search(sibling.string.strip())
try:
f.writelines("\t" + date[1] + '-' + date[2] + '-' + date[3])
except TypeError:
continue
if sibling.attrs["class"] == ['rateInfo']:
try:
f.writelines("\t" + sibling.contents[3].string.strip('\n'))
except IndexError:
f.writelines("\t0")
continue
except AttributeError:
continue
f.writelines("\n")
f.close()
# timeList = soup.find_all(attrs={"class": "info tip"})
# for time in timeList:
# f.writelines(time.string)
- ここでの最終的な結果は表示しないようです -