DAY03:lxml

html_doc = """
<html><head><title>The Dormouse's story</title></head>
<body><p class="sister"><b>$37</b></p>
<p class="story" id="p">Once upon a time there were three little sisters;
and their names were<a href="http://example.com/elsie" class="sister" >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>
"""' ''String filter'' '# find the document search find_all#text matching text#attrs attribute lookupto the #NAME tag nameSoup = the BeautifulSoup (html_doc, 'lxml')

Import the BeautifulSoup BS4 from










p = soup.find(name='p')
p_s = soup.find_all(name='p')

print(p)
pirnt(p_s)

#name+attrs
p = soup.find(name='p',attrs={"id":"p"})
print(p)

#name+text
tag = soup.find(name='title',text="The Dormouse's story")
print(tag)
a_s = soup.find_all(name=re.compile('a'))
print(a_s)

#attrs
a = soup.find(attrs={"id":re.compile('link')})
print(a)

#列表过滤器
#列表内的数据匹配
print(soup.find(name=['a','p','html',re.compile('a')]))
print(soup.find_all(name=['a','p','html',re.compile('a')])) # to be used in some of the attributes and attribute lookup unwanted# Filter MethodPrint (soup.find (name = True, attrs = { "ID": True}))#true Match

#Bool filter






def have_id_not_class(tag):
#pirnt(tag.name)
if tag.name == 'p' and tag.has_attr("id") and not tag.has_attr("class"):
return tag

#print(soup.find_all(name=函数对象))
print(soup.find_all(name=have_id_not_class))

#补充知识点
#id
a = soup.find(id = 'link2')
print(a)

#class
p=soup.find(class_='sister')
print(p)

Guess you like

Origin www.cnblogs.com/friendg/p/11129339.html