ホームページ  >  記事  >  バックエンド開発  >  Python は beautifulSoup を使用してクローラーを実装します

Python は beautifulSoup を使用してクローラーを実装します

PHP中文网
PHP中文网オリジナル
2017-06-01 10:20:141654ブラウズ

Web ページ www.jb51.net/article/55789.htm をクロールするために phantomjs を使用することについては以前に説明しました。これは、セレクター

を使用して行われます (ドキュメント: www.crummy.com/software)。 /BeautifulSoup/ bs4/doc/) この Python モジュールは Web コンテンツを簡単にキャプチャできます


# coding=utf-8
import urllib
from bs4 import BeautifulSoup

url ='http://www.baidu.com/s'
values ={'wd':'网球'}
encoded_param = urllib.urlencode(values)
full_url = url +'?'+ encoded_param
response = urllib.urlopen(full_url)
soup =BeautifulSoup(response)
alinks = soup.find_all('a')

Baidu の検索結果をキャプチャでき、結果はテニスの記録です。

beautifulSoup には非常に便利なメソッドが多数組み込まれています。

いくつかの便利な機能:

ノード要素を構築します

コードは次のとおりです:

soup = BeautifulSoup('
Extremely bold
')
tag = soup.b
type(tag)
#

属性は attr を使用して取得できます。 、結果は辞書

で、コードは次のとおりです:

tag.attrs
# {u'class': u'boldest'}

または、tag.class から属性を直接取得できます。

属性を自由に操作することもできます


tag['class'] = 'verybold'
tag['id'] = 1
tag
#Extremely bolddel tag['class']
del tag['id']
tag
#Extremely boldtag['class']
# KeyError: 'class'
print(tag.get('class'))
# None

次の例のように dom 要素を検索するために自由に操作することもできます

1. ドキュメントを作成します


html_doc = """The Dormouse's storyThe Dormouse's storyOnce upon a time there were three little sisters; and their names wereElsie,Lacie andTillie;
and they lived at the bottom of a well...."""

from bs4 import BeautifulSoup
soup = BeautifulSoup(html_doc)

2. さまざまな作業を行います


声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。