领英模拟登陆

本文详细介绍了使用Python模拟登录领英网站的过程,包括获取必要参数如loginCsrfParam、cookie和csrf_token的方法,以及如何利用这些参数实现模拟登录。通过具体代码示例,读者可以学习到如何使用requests和lxml库完成这一过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

说明

上一篇文章已经爬虫目的, 脉脉模拟登陆

领英模拟登陆难度略大于脉脉

操作

1、登陆接口

其中session_key是用户名,session_password是密码。

关键点

1、loginCsrfParam

2、cookie

3、csrf_token

寻找参数

1、loginCsrfParam

这个参数是你访问领英首页就会响应的一个结果,可以通过xpath定位

//input[@id="loginCsrfParam-login"]/@value

2、cookie

此时的cookie是并没有进行登陆的cookie,此时我们需要保存本次的cookie,因为模拟登陆的接口是需要本次cookie的。

3、csrf_token

这个参数是和loginCsrfParam成对出现的,当你携带loginCsrfParam访问了首页,在首页的响应cookie中,会有JSESSIONID字段,JSESSIONID字段的值就是csrf_token的值。

当我们把所有的参数都找到之后就可以直接模拟登陆了。

完整代码

 

import requests
from lxml import etree
import demjson

class Login:
    def __init__(self):
        # 输入用户名和密码
        self.username = ""
        self.password = ""

    def get_index_csrf_and_cookie(self):
        session = requests.Session()
        url = "https://www.linkedin.com/"
        querystring = {"trk": "brandpage_baidu_pc-mainlink"}
        headers = {
            'authority': "www.linkedin.com",
            'cache-control': "max-age=0,no-cache",
            'upgrade-insecure-requests': "1",
            'user-agent': "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.109 Safari/537.36",
            'accept': "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
            'referer': "https://www.baidu.com/s?ie=UTF-8&wd=%E9%A2%86%E8%8B%B1",
            'accept-encoding': "gzip, deflate, br",
            'accept-language': "zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7",
        }
        response = session.request("GET", url, headers=headers, params=querystring)
        cookie = ""
        csrf_token = ""
        for c in session.cookies:
            if c.name == "JSESSIONID":
                csrf_token = c.value
            cookie = cookie + c.name + "=" + c.value + "; "
        html = etree.HTML(response.text)
        csrf = html.xpath('//input[@id="loginCsrfParam-login"]/@value')[0]
        index_login_data = {
            "cookie": cookie,
            "csrf": csrf,
            "csrf_token": csrf_token
        }
        with open("index_cookie.json", "w") as f:
            f.write(str(index_login_data))

    def login(self):
        with open("index_cookie.json", "r") as f:
            index_cookie = f.read()
        json_cookie = demjson.decode(index_cookie)
        csrf = json_cookie.get("csrf")
        cookie = json_cookie.get("cookie")

        s = requests.session()

        url = "https://www.linkedin.com/uas/login-submit"

        querystring = {"loginSubmitSource": "GUEST_HOME"}

        payload = "session_key={0}&session_password={1}&isJsEnabled=false&loginCsrfParam={2}&fp_data=default&undefined=".format(self.username, self.password, csrf)
        headers = {
            'authority': "www.linkedin.com",
            'cache-control': "max-age=0,no-cache",
            'origin': "https://www.linkedin.com",
            'upgrade-insecure-requests': "1",
            'content-type': "application/x-www-form-urlencoded",
            'user-agent': "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.109 Safari/537.36",
            'accept': "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
            'referer': "https://www.linkedin.com/",
            'accept-encoding': "gzip, deflate, br",
            'accept-language': "zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7",
            'cookie': cookie
        }

        s.request("POST", url, data=payload, headers=headers, params=querystring)

        cookie = ""
        csrf_token = ""
        for c in s.cookies:
            if c.name == "JSESSIONID":
                csrf_token = c.value
            cookie = cookie + c.name + "=" + c.value + "; "

        cookie_data = {
            "cookie": cookie,
            "csrf_token": csrf_token
        }
        with open("cookie.json", "w") as f:
            f.write(str(cookie_data))



    def test_login(self):
        with open("cookie.json", "r") as f:
            cookie_text = f.read()
        json_cookie = demjson.decode(cookie_text)
        csrf_token = json_cookie['csrf_token']
        cookie = json_cookie['cookie']



        headers1 = {
            'x-li-track': '{"clientVersion":"1.2.7373","osName":"web","timezoneOffset":8,"deviceFormFactor":"DESKTOP","mpName":"voyager-web"}',
            'cookie': cookie,

            'accept-encoding': "gzip, deflate, br",
            'x-li-lang': "zh_CN",
            'accept-language': "zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7",
            'user-agent': "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.109 Safari/537.36",
            'x-li-page-instance': "urn:li:page:d_flagship3_feed;LvtQ1iY2QeGSOhIoA8jaQQ==",
            'accept': "application/vnd.linkedin.normalized+json+2.1",
            'csrf-token': csrf_token.replace('"', ""),
            'x-restli-protocol-version': "2.0.0",
            'authority': "www.linkedin.com",
            'referer': "https://www.linkedin.com/feed/",
            'cache-control': "no-cache",
        }

        url = "https://www.linkedin.com/feed/"

        response = requests.request("GET", url, headers=headers1)
        response.encoding = "utf-8"
        print(response.text)
        # u = "https://www.linkedin.com/voyager/api/onboarding/launchpadCard"
        # querystring = {"context": "FEED", "q": "context"}
        # r = requests.get(u, headers=headers1, params=querystring)
        # print(r.text)


if __name__ == "__main__":
    login = Login()
    # login.get_index_csrf_and_cookie()
    # login.login()
    # with open("index_cookie.json", "r") as f:
    #     session = f.read()
    #     se = demjson.decode(session)
    # print(se.get("csrf_token"))
    #
    # with open("cookie.json", "r") as f:
    #     cookie = f.read()
    #     json_cookie = demjson.decode(cookie)
    # print(json_cookie['cookie'])

    login.test_login()

 

### 构建或使用 LinkedIn 爬虫的方法 LinkedIn 数据抓取是一个涉及技术实现、法律合规性和道德考量的过程。以下是关于如何构建或使用 LinkedIn 爬虫的相关信息。 #### 法律与道德注意事项 直接通过爬虫获取 LinkedIn 的数据不仅违反了平台的服务条款,还可能导致法律责任[^2]。因此,在考虑开发或部署 LinkedIn 爬虫之前,务必了解并遵循相关法律法规以及 LinkedIn 提供的官方 API 政策。 --- #### 使用 LinkedIn 官方 API 进行数据采集 为了合法地访问 LinkedIn 平台上的数据,推荐使用 LinkedIn 开发者门户中的官方 API。这是一套经过授权的方式,能够安全且高效地提取所需信息。虽然该方法存在一定的限制(如请求频率和数据范围),但它是最可靠的选择之一。 - **注册开发者账户**:前往 [LinkedIn Developers](https://developer.linkedin.com/) 注册成为开发者。 - **创建应用**:生成 OAuth 令牌以便于后续的身份验证过程。 - **调用 RESTful 接口**:根据需求选择合适的端点(Endpoints)来检索目标资源,例如用户档案、工作机会或者公司详情。 示例代码如下: ```python import requests def fetch_linkedin_data(access_token, endpoint_url): headers = { 'Authorization': f'Bearer {access_token}', 'Content-Type': 'application/json' } response = requests.get(endpoint_url, headers=headers) if response.status_code == 200: return response.json() else: raise Exception(f"Error fetching data: {response.text}") # 替换为实际的 Access Token 和 Endpoint URL ACCESS_TOKEN = "your_access_token_here" ENDPOINT_URL = "https://api.linkedin.com/v2/me" try: user_profile = fetch_linkedin_data(ACCESS_TOKEN, ENDPOINT_URL) print(user_profile) except Exception as e: print(e) ``` --- #### 基于 Python 的第三方库——LinkedIn Scraper 如果确实需要一种更灵活的方式来收集公开可用的数据,则可以借助开源社区维护的一些工具包,比如 `linkedin-scraper`[^3]。这类解决方案通常依赖 Selenium 技术驱动真实浏览器实例完成交互任务,并自动解析页面内容从而获得结构化结果。 注意的是,尽管这些脚本可以帮助我们快速搭建原型系统,但由于它们并未得到 LinkedIn 认可,所以在大规模生产环境中应谨慎采用此类手段。 安装命令: ```bash pip install linkedin-scraper ``` 基本用法展示: ```python from linkedin_scraper import Person person = Person("https://www.linkedin.com/in/example", driver=None) print(person.name) # 输出姓名字段值 print(person.experience) # 打印工作经验列表 ``` > 特别提醒:运行上述程序前需配置好 ChromeDriver 路径环境变量,具体参见文档说明链接。 --- #### 面临的技术挑战 即便有了现成框架辅助编写 LinkedIn 爬虫逻辑,仍然会遇到不少棘手问题亟待解决[^4]: 1. 登录机制复杂多变; 2. 动态加载 HTML 元素难以定位; 3. 反爬策略频繁升级调整; 4. IP 地址容易被封禁处理等等... 针对这些问题,建议采取以下措施缓解影响程度: - 实施代理轮询降低单一出口压力; - 设置合理的延时间隔避免触发检测规则; - 更新 XPath/CSS Selectors 表达式适配最新 DOM 结构变化。 ---
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值