python

python - BeautifulSoup 简单使用

2019-08-22  本文已影响0人  精神病患者link常
# -*- coding: UTF-8 -*-

import urllib2, re, urllib, socket
from bs4 import BeautifulSoup

def SoupHtml(html):
    soup = BeautifulSoup(html, "html.parser")

html = '''
<li>
    <h5>
        <a href="/html/132663.htm" title="2019七夕早安图片大全 七夕情人节鲜花花束图片" target="_blank">2019七夕早安图片大全 七夕情人节鲜花花束图片</a>
    </h5>
    <div class="cover">
        <a href="/html/132663.htm" title="2019七夕早安图片大全 七夕情人节鲜花花束图片" target="_blank">
            <img src='//pic.feizl.com/upload/allimg/190808/gxtxfcgtvdxvmpo.jpg' border='0' width='160' height='110'>
        </a>
    </div>
    <a id="love" class="like" href="javascript:" onClick="javascript:postDigg('good',132663)">
    </a>
    <div class="date" id="test">发布时间:2019-08-08</div>
</li>
'''
SoupHtml(html)

find 查询一个标签

print soup.find(class_="cover") # class 是关键字  所有使用class_
或者
print soup.find(attrs={'class': 'cover'})
print soup.find(id="test")
或者
print soup.find(attrs={'id': 'test'})
print soup.find(class_="like").get("id")
print soup.find('a', id="love").get("href")
print soup.find('div', id="test").get_text()
print soup.find('a', id="love").attrs
print soup.find(class_="cover").children # listiterator object at 0x10da27890> 需通过遍历得到
for i in soup.find(class_="cover").children:  
    print(i) # 标签
print soup.find(id="love").has_attr("title")

find_all 查询多个标签

print soup.find_all('div', class_=re.compile("da"))
print soup.find_all('div')
print soup.find_all('div', id="test")
print soup.find_all(['a', 'div'])
print soup.find_all(id="love")
print soup.find_all(id=["love", "test"])

select 查询多个标签

print soup.select('a')
print soup.select('.like')
print soup.select('#test')
print soup.select('a #test')
上一篇下一篇

猜你喜欢

热点阅读