pip install bs4
BS4的4中对象
BeautifulSoup对象
from bs4 import BeautifulSoup import requests res = request.get(‘http://www.baidu.com‘) response=res.text() soup = BeautifulSoup(response.text,‘html.parser‘) return soup.find(name=‘title‘)
soup.a.attrs 返回一字典,里面是所有属性和值
soup.a[‘href‘] 获取href属性
soup.a.string
soup.a.text
soup.a.get_text()
【注】当标签里面还有标签的时候,string获取的为None,其他两个获取纯文本内容
soup.find(‘a‘)
soup.find(‘a‘, class_=‘xxx‘)
soup.find(‘a‘, title=‘xxx‘)
soup.find(‘a‘, id=‘xxx‘)
soup.find(‘a‘, id=re.compile(r‘xxx‘))
【注】find只能找到符合要求的第一个标签,他返回的是一个对象
返回一个列表,列表里面是所有的符合要求的对象
soup.find_all(‘a‘)
soup.find_all(‘a‘, class_=‘wang‘)
soup.find_all(‘a‘, id=re.compile(r‘xxx‘))
soup.find_all(‘a‘, limit=2) 提取出前两个符合要求的a
选择,选择器 css中
常用的选择器
标签选择器、id选择器、类选择器
层级选择器**
div h1 a 后面的是前面的子节点即可
div > h1 > a 后面的必须是前面的直接子节点
属性选择器
input[name=‘hehe‘]
select(‘选择器的‘)
【注】返回的是一个列表,列表里面都是对象
【注】find find_all select不仅适用于soup对象,还适用于其他的子对象,如果调用子对象的select方法,那么就是从这个子对象里面去找符合这个选择器的标签
pip install lxml
原文:https://www.cnblogs.com/TodayWind/p/14907997.html