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

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

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

selector选择器快速查找标签方法_第1张图片
image

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

selector选择器快速查找标签方法_第2张图片
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)    #返回的结果是列表类型
selector选择器快速查找标签方法_第3张图片
image

你可能感兴趣的:(selector选择器快速查找标签方法)