美文网首页
selector选择器快速查找标签方法

selector选择器快速查找标签方法

作者: libdream | 来源:发表于2018-12-26 10:12 被阅读0次

selector选择器是Python爬虫中和find()、find_all()一样常见的用来查找网页标签的方法,其使用方法类似中国>湖南省>长沙市,从大到小提取需要的信息,这种方式可通过谷歌浏览器、360浏览器、火狐浏览器等复制得到。具体操作如下:

(1)鼠标定位到想提取的数据位置,右击,在弹出的快捷菜单中选择“检查”命令。(各浏览器具体叫法不一样,功能差不多,比如360叫审查元素)

image

(2)在网页源代码中右击所选元素,在弹出的快捷菜单中选择 Copy selector

image

(3)得到#headLineDefault > ul > ul:nth-child(1) > li:nth-child(2) > a,需要注意的是,li:nth-child在Python中运行会报错,需改为li:nth-of-type,其他保持不变即可。

具体代码如下:

import requests
from bs4 import BeautifulSoup

headers = {'User-Agent':'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 \
(KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36'}

r = requests.get("http://www.ifeng.com/", headers=headers)
if r.encoding == 'ISO-8859-1':            #解决中文乱码问题
    encodings = requests.utils.get_encodings_from_content(r.text)
    if encodings:
        encoding = encodings[0]
    else:
        encoding = r.apparent_encoding
encode_content = r.content.decode(encoding, 'replace').encode('utf-8', 'replace')
soup = BeautifulSoup(encode_content, 'lxml')
firstNews = soup.select('#headLineDefault > ul > ul:nth-of-type(1) > li:nth-of-type(2) > a')    #注意这两处需要修改,不能直接使用复制过来的
print(firstNews)    #返回的结果是列表类型
image

相关文章

  • selector选择器快速查找标签方法

    selector选择器是Python爬虫中和find()、find_all()一样常见的用来查找网页标签的方法,其...

  • jquery学习

    $("selector")支持所有css选择器 $("selector",dom)从指定dom中根据选择器查找元素...

  • pyquery

    什么是pyquery? find(selector) : 使用css选择器查找filter(selector) :...

  • IE兼容document.getElementsClassNam

    /** * 根据选择器查找元素 * @param selector选择器,可取 #id .class el...

  • 运用$来封装函数,实现元素的查询

    一、tools编写/** 根据选择器查找元素 @param selector 选择器,可取 #id .cl...

  • CSS语法

    选择器(selector):使用选择器来选择需要添加样式的标签。CSS属性(property):给选择的标签添加什...

  • CSS基础

    CSS语法 selector{property:value}1.CSS选择器选择器主要分为三种元素选择器:通过标签...

  • jQuery

    $(selector).action()美元符号定义jQuery选择器查找HTML元素action()执行对元素的...

  • k8s中yaml配置

    1.deployment配置文件 labels标签 放在metadata里,selector选择器中匹配的标签要和...

  • Selector syntax sugar

    Selector(方法选择器)在target-action模式中必不可少的,通过Selector可以找到指定的方法...

网友评论

      本文标题:selector选择器快速查找标签方法

      本文链接:https://www.haomeiwen.com/subject/nlgclqtx.html