欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

网络爬虫(五)之解析网页【XPath】

程序员文章站 2024-01-27 14:13:34
...

网络爬虫(五)之解析网页【XPath】

案例:练习使用XPath

"""
案例:练习使用XPath
"""
from lxml import etree

# 这是让我们联系的数据
html_doc = """
<div>
    <ul>
        <li class="item-0"><a href="www.baidu.com">baidu</a>
        <li class="item-1 one" name="first"><a href="https://blog.csdn.net/qq_25343557">myblog</a>
        <li class="item-1 two" name="first"><a href="https://blog.csdn.net/qq_25343557">myblog2</a>
        <li class="item-2"><a href="https://www.csdn.net/">csdn</a>
        <li class="item-3"><a href="https://hao.360.cn/?a1004">bbb</a>
        <li class="aaa"><a href="https://hao.360.cn/?a1004">aaa</a>
"""

# 把网页进行初始化(这里补全网页加上 html 标签)
html = etree.HTML(html_doc)
# 这是找到 a标签 hef属性为 https://hao.360.cn/?a1004 的 父亲的 class属性
lis = html.xpath("//a[@href='https://hao.360.cn/?a1004']/../@class")
# 这是a标签的所有文本
lis = html.xpath("//a/text()")
# 获取不到 因为 item-1 one 这是说 class的值为 item-1 one
# 要想找到可以写成 @class='item-1 one'
lis = html.xpath("//li[@class='item-1']")
# 这是代表 class这个属性中包含 item-1 所以这个能匹配到
lis = html.xpath("//li[contains(@class,'item-1')]")
#这是找class属性中以 item-开头的值
lis = html.xpath("//li[starts-with(@class,'item-')]/a/text()")
# 这是多值匹配 通过 and 符号链接
lis = html.xpath("//li[contains(@class,'one') and @name='first']")

print(len(lis))
for v in lis:
    print(type(v))

综合案例:爬取《51job》相关职位信息,并保存成csv文件格式

"""
案例:爬取《51job》相关职位信息,并保存成csv文件格式
"""
import requests
from lxml import etree
import csv
import time


# 设置请求头,模拟浏览器去获取数据,所以要带这个请求头,但是一定要使用自己的
header = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.25 Safari/537.36 Core/1.70.3741.400 QQBrowser/10.5.3863.400",
}

f = open("python职位.csv", "w", newline="")
writer = csv.writer(f);
writer.writerow(['编号', '职位名称', '公司名称', '薪资', '地址', '发布时间'])

i = 1
for page in range(1, 159):
    response = requests.get(f"https://search.51job.com/list/020000,000000,0000,00,9,99,python,2,{page}.html?lang=c&stype=&postchannel=0000&workyear=99&cotype=99&degreefrom=99&jobterm=99&companysize=99&providesalary=99&lonlat=0%2C0&radius=-1&ord_field=0&confirmdate=9&fromType=&dibiaoid=0&address=&line=&specialarea=00&from=&welfare=", headers=header)
    response.encoding="gbk"
    if response.status_code == 200:
        html = etree.HTML(response.text)
        # 这里找到 div中class属性为 el 的所有元素 ,起始位置为 4
        els = html.xpath("//div[@class='el']")[4:]
        for el in els:
            jobname = str(el.xpath("p[contains(@class,'t1')]/span/a/@title")).strip("[']")
            jobcom = str(el.xpath("span[@class='t2']/a/@title")).strip("[']")
            jobaddress = str(el.xpath("span[@class='t3']/text()")).strip("[']")
            jobmoney = str(el.xpath("span[@class='t4']/text()")).strip("[']")
            jobdate = str(el.xpath("span[@class='t5']/text()")).strip("[']")
            writer.writerow([i, jobname, jobcom, jobaddress, jobmoney, jobdate])
        print(f"第{page}页获取完毕")

运行结构:

网络爬虫(五)之解析网页【XPath】
网络爬虫(五)之解析网页【XPath】