BeautifulSoup 爬虫入门Ⅰ

BeautifulSoup4安装

pycharm 直接在setting 里面找到 Beautifulsoup4 install就好
注意:

  • interpreter 要知道是下在了哪一个
  • 编译时记得查看 edit configuration 的interpreter 是否对应

用 BeautifulSoup 简单爬一个对象

from urllib.request import urlopen
from bs4 import BeautifulSoup
html= urlopen('https://www.pythonscraping.com/pages/page1.html')
bs=BeautifulSoup(html.read(),'html.parser')
print(bs.h1)

网站可以换,h1 也可以换成其它标签

防止一些错误的方法

当找不到网页或者找不到网页所在服务器或者网页上的内容不是要找到 都会出现异常
下面函数能够检查包括URL输入错误的几个问题。

def getTitle(url):
    try:
        html = urlopen(url)
    except HTTPError as e:#网页不存在
            return None
    try:
        bs = BeautifulSoup(html.read(), 'html.parser')
        title=bs.body.h1
    except Attributerror as e:#URL输入错误和服务器不存在
            return None
            return title


title=getTitle('https://www.pythonscraping.com/pages/page1.html')
if title == None:#出现任何问题
    print('no paragraph')
else:
    print(title)

find 和 find_all

find(tag,attributrs,recursive,text,keywords)
find_all(tag,attributes,recursive,text,keywords)

tag就是HTML里面的标签
attributes 用dict 字典把标签和标签对应的值封装
recursive bool量 想要抓取多少层的标签信息
keyword 【tag是标签间“或”的方式获取】 keyword查找关键词 实现一个“与”的逻辑

from urllib.request import urlopen
from bs4 import BeautifulSoup
html = urlopen('https://www.pythonscraping.com/pages/page1.html')
bs = BeautifulSoup(html.read(),'html.parser')
nameL = bs.findAll('span', {'class' : 'green'})
for name in nameL:
    print(name.gte_text())
关于get_text()

函数会清除所有标签并只返回一个只包含文字的字符串‘(清楚其他的段落、超链接)

导航树 (navigating trees)

子标签与后代标签

子标签**.children()** 只显示后一层的node
后代标签 .descendants() 显示后面所有层的标签

from urllib.request import urlopen
from bs4 import BeautifulSoup

html = urlopen("http://www.pythonscraping.com/pages/page3.html")
bs = BeautifulSoup(html,"html.parser")
for child in bs.find("table",{"id":"giftList"}).children:
    print(child)
兄弟标签

显示后面的兄弟标签 (不包括调用的自身giftList 标签)

# 前面部分一样的
for bro in bs.find("table",{"id":"giftList"}).tr.next_sibling:
    print(bro)
正则表达式regex

正则可以挑选符合表达式规范的字符串并返回
但具体表达式的构建有些复杂 贴了文件 需要就去查看

regexpal 网站

from urllib.request import urlopen
from bs4 import BeautifulSoup
import re
html = urlopen("http://www.pythonscraping.com/pages/page3.html")
bs = BeautifulSoup(html,"html.parser")
image=bs.find_all('img',
{'src':re.compile('\.\.\/img\/gifts\/img.*\.jpg')})#正则表达式
for img in image:
    print(img['src'])

Lambda表达式

进行函数的嵌套,一个函数作为变量(返回Bool型结果)套入另一个函数

html = urlopen("http://www.pythonscraping.com/pages/page3.html")
bs = BeautifulSoup(html,"html.parser")
image=bs.find_all(lambda tag: len(tag.attrs) == 2)
for img in image:
    print(img)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值