python爬取微博的粉丝列表、关注列表、微博文本列表

本文的全部代码放到了github上,github地址为https://github.com/ximingren/clawer_sumary

整个爬虫的流程是  获取cookie---->根据昵称获取用户的相关信息---->获取关注列表---->获取粉丝列表---->获取微博文本列表

下面的内容分为几部分

一.获取cookie

    driver = webdriver.Chrome(driver_path)  # 打开Chrome
    driver.maximize_window()  # 将浏览器最大化显示
    driver.get(weibo_url)  # 打开微博登陆页面
    time.sleep(10)  # 加载页面需要时间,延时10s来确保页面已加载完毕
    time.sleep(2)
    driver.find_element_by_name("username").send_keys(username)  ##输入用户名
    driver.find_element_by_name("password").send_keys(password)  ##输入密码
    driver.find_element_by_xpath("//a[@node-type='submitBtn']").click()  ##点击登录按钮
    cookies = driver.get_cookies()  ##获取cookies
    cookie = ""
    # 将返回的Cookies数组转成微博需要的cookie格式
    for x in range(len(cookies)):
        value = cookies[x]['name'] + "=" + cookies[x]['value'] + ";"
        cookie = cookie + value
    return cookie

上述代码中我们用了webdriver这个库来获取cookie.webdriver用来打开游览器,driver.get_cookies()则获取所有的cookie。然后对cookie进行分割处理,最后返回处理后的cookie

二.添加headers用requests等库模拟登陆

        headers['Cookie']=cookie
        info_response = requests.get('http://s.weibo.com/user/' + names_list[x], headers)  # 微博搜索的页面url
        info_soup = BeautifulSoup(info_response.text, 'html5lib')  # 利用BeautifulSoup库进行解析html操作
        info_soup = get_html(info_soup, "pl_user_feedList")
        weibo_info = info_soup.find_all('a', attrs={"class": "W_linkb", "target": "_blank"})  # 找到用户信息的html
        id = weibo_info[0].get('href')  # 用户id
        subs_size = weibo_info[0].string  # 关注数
        fans_size = weibo_info[1].string  # 粉丝数
        contents_size = weibo_info[2].string  # 微博数
        subs_size = int(re.sub("\D", "", subs_size))  # 只取出数字,其它的不管用,下面同理
        fans_size = int(re.sub("\D", "", fans_size))
        contents_size = int(re.sub("\D", "", contents_size))
        id = int(re.findall('\d+', id)[0])
        return [subs_size, fans_size, contents_size, id]

上述代码中我们将通过driver得到的cookie加入到headers中,然后在通过requests.get()访问得到网页的时候加入header。将html代码用BeautifulSoup解析。将相关信息处理后返回关注者数、粉丝数、微博数.

三.获取关注者列表

  for page in range(1, subs_list_size + 1):
            subs_url = "https://weibo.com/p/100505" + weibo_id + "/follow?page=" + str(page) + "#Pl_Official_HisRelation__59"  # 拼凑成关注者列表的页面url
            subs_request = Request(subs_url, headers=headers)
            subs_response = urlopen(subs_request)
            subs_html = subs_response.read().decode()
            subs_soup = BeautifulSoup(subs_html, 'html5lib')
            subs_soup = get_html(subs_soup, "WB_cardwrap S_bg")
            subs_list = subs_soup.find_all('a', attrs={"class": "S_txt1", "target": "_blank"}) #关注者列表

上述我们用到了Request这个函数,如果用requests的话返回的是登陆的页面,这里有点搞不明白。同时,获取粉丝数列表的操作类似。

四.获取微博文本列表

            params = urllib.parse.urlencode(
                {'__rnd': get_timestamp(), 'page': page, 'pagebar': pagebar, "id": "100505" + weibo_id,
                 "script_uri": "/p/" + "100505" + weibo_id,
                 'ajwvr': 6, 'domain': 100505, "pl_name": "Pl_Official_MyProfileFeed__22", "profile_ftype": 1,
                 'feed_type': 0, 'domain_op': 100505}).encode()  # 调用接口时所用的参数
            request = Request(api_url + "?%s" % (params).decode(), headers=headers)
            print("---------------请求连接到微博内容页面")
            response = urlopen(request)
            html = response.read().decode('utf8')  # 对调用接口后传过来的内容进行解码
            html_start = html.find("<div")  # 获取最前面的div标签
            html_end = html.rfind("div>")  # 获取最后面的div标签
            parser_html = html[html_start:html_end + 4]
            cont_html = parser_html.replace('\\"', '"')  # 进行适当的处理
            cont_html = cont_html.replace('\\/', '/')
            print("-----------------解析微博文本内容%d次" % count)
            cont_soup = BeautifulSoup(cont_html, 'html5lib')  # 进行解析
            text_list = cont_soup.find_all('div', attrs={"class": 'WB_text W_f14', "node-type": "feed_list_content"})  # 文本列表
            time_list = cont_soup.find_all('a', attrs={"class": 'S_txt2', 'node-type': "feed_list_item_date"})  # 时间列表
            phone_list = cont_soup.find_all('a', attrs={"action-type": "app_source"})  # 手机型号列表
              

上述代码我调用了微博的接口进行分析,首先传参数到接口url,然后接口返回html代码。对代码进行解析处理即可得到微博文本内容。

猜你喜欢

转载自blog.csdn.net/ximingren/article/details/81204565