【python爬虫】BeautifulSoup库的选择器select()方法
2018-02-20 09:15
453 查看
一般使用BeautififulSoup解析得到的Soup文档可以使用
F12中选择了目标element之后,右键—Copy—Copy selector 如图:
如果所复制的选择器中包含
demo:
find_all()、
find()、
select()方法定位所需要的元素。
find_all()是获得list列表、
find()是获得map一条数据。
select()是根据选择器可以获得多条也可以获得单条数据。一般最常用的是
find_all()和
find()两个参数。
select()方法的使用
从页面中自定义获得选择器:F12中选择了目标element之后,右键—Copy—Copy selector 如图:
nth-child在Python中运行会报错,需要改为
nth-of-type:
如果所复制的选择器中包含
nth-child,则需要改为
nth-of-type,否则会报错。
demo:
import requests from bs4 import Beauti 4000 fulSoup url = 'http://www.cnplugins.com/' headers = { 'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.140 Safari/537.36'} res = requests.get(url,headers = headers) #get方法中加入请求头 #查看下当前requests请求url抓去的数据编码,这里获取的是ISO-8859-1 print (requests.get(url).encoding) #翻阅下要爬去的网站的编码是什么,这里看了下是utf-8,编码不一样会乱码,将requests获取的数据编码改为和目标网站相同,改为utf-8 res.encoding = 'utf-8' soup = BeautifulSoup(res.text, 'html.parser') #对返回的结果进行解析 # print (soup.select('body > section > div.wrapbox > div:nth-child(1) > div > ul > li:nth-child(6)')) # nth-child 在python中运行会报错,需改为 nth-of-type # print (soup.select('body > section > div.wrapbox > div:nth-of-type(1) > div > ul > li:nth-of-type(6)')) textlist = soup.select('body > section > div.wrapbox > div > div > ul > li > div.iimg-box-meta > a') for t in textlist: print (t) #获取单条html信息 print (t.get_text()) #获取中间文字信息
相关文章推荐
- python爬虫:BeautifulSoup 使用select方法的使用
- python爬虫之BeautifulSoup 使用select方法详解
- Python 网络爬虫-正则表达式、BeautifulSoup、lxml三种提取方法
- [置顶] python爬虫还在用BeautifulSoup?你有更好的选择!
- Python BeautifulSoup4 select方法执行css选择器
- 用python做爬虫的多种方法选择
- python爬虫里信息提取的核心方法: Beautifulsoup、Xpath和正则表达式
- python爬虫由浅入深3--BeautifulSoup的使用的基本方法
- 两种模型选择和超参数调整方法及Spark MLlib使用示例(Scala/Java/Python)
- 讲解Python的Scrapy爬虫框架使用代理进行采集的方法
- Python爬虫之三种网页抓取方法性能比较
- python3个人爬虫之:BeautifulSoup学习心得
- python爬虫(1)利用BeautifulSoup进行网络数据采集
- select默认选择的实现方法
- Python爬虫正则表达式常用符号和方法
- IMap.SelectByShape 方法选择要素
- 以Python的Pyspider为例剖析搜索引擎的网络爬虫实现方法
- python简单爬虫,Beautifulsoup4解析,爬取直播吧部分热门新闻及链接
- JS左边select内容选择到右边select内容里面的js实现方法(可以多选和全选)