爬虫之BeautifulSoup

beautifulsoup的语法:

find_all方法:搜索出所有满足要求的结点

find方法:搜索出满足要求的第一个结点

搜索结点:

find_all,find
方法:find_all(name,attrs,string); #结点的名字,结点的属性,结点的文字;

#查找所有标签为a的结点:
soup.find_all(‘a’);

#查找所有标签为a,连接符合/view/123.html形式的结点

soup.find_all(‘a’,href=’/view/123.html’)
soup.find_all(‘a’,href=re.compile(r’/view/123.html’))

#查找所有标签为div,class为abc,文字为python的结点:
soup.findall(‘div’,class=’abc’,string=”python”);

例如:

1
2
3
4
5
6
7
from bs4 import BeautifulSoup
soup=BeautifulSoup(html_doc, #HTML文档字符串
html.parser' #HTML解析器
from_encoding='utf-8' #HTML文档的编码
)

###(2)访问节点的信息:
得到节点python

#获取查找的结点的标签名称:
node.name;

#获取查找到的a结点的href属性:
node[‘href’];

#获取查找到的a结点的连接文字:
node.get_text();

实例:

        from bs4 import BeautifulSoup
import re
html_doc = """
<html><head><title>The Dormouse's story</title></head>
<body>
<p class="title"><b>The Dormouse's story</b></p>

<p class="story">Once upon a time there were three little sisters; and their names were
<a href="http://example.com/elsie" class="sister" id="link1">Elsie</a>,
<a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and
<a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>;
and they lived at the bottom of a well.</p>

<p class="story">...</p>
"""

soup=BeautifulSoup(html_doc,'lxml',from_encoding='utf-8')


print ("lian jie")

links=soup.find_all('a')

for link in links:
    print(link.name,link['href'],link.get_text())
print ("-----------------------")

link_node=soup.find('a',href="http://example.com/lacie")

print(link_node.name,link_node['href'],link_node.get_text())


print("--------正则表达式----------")
link_n=soup.find('a',href=re.compile(r"ill"))
print(link_n.name,link_n['href'],link_n.get_text())


print("获取p段落里的文字")
link_no =soup.find('p',class_="title")

print(link_no.name,link_no.get_text())
Fork me on GitHub