python爬虫爬取博客园

打印 上一主题 下一主题

主题 926|帖子 926|积分 2778

python 爬取 博客园 接 蚂蚁学pythonP5生产者消费者爬虫数据重复问题


  • 先看访问地址


    • 访问地址是https://www.cnblogs.com/#p2 但是实际访问地址是https://www.cnblogs.com 说明其中存在猫腻;像这种我们给定指定页码,按理应该是 post 请求才对;于是乎 往下看了几个连接

    • 然后再看一下payload 发现这个post 请求 才是我们想要的链接 其中PageIndex 就是我们要设置的页数


  • 代码撸起来
    1. # Author: Lovyya
    2. # File : blog_spider
    3. import requests
    4. import json
    5. from bs4 import BeautifulSoup
    6. import re
    7. # 这个是为和老师的urls一致性 匹配urls里面的数字
    8. rule = re.compile("\d+")
    9. urls = [f'https://www.cnblogs.com/#p{page}' for page in range(1, 31)]
    10. # pos请求网址
    11. url = "https://www.cnblogs.com/AggSite/AggSitePostList"
    12. headers = {
    13.         "content-type": "application/json",
    14.         "user-agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/95.0.4638.54 Safari/537.36 Edg/95.0.1020.30"
    15. }
    16. def craw(urls):
    17.         #idx 是'xxx.xxxx.xxx/#p{num}' 里面的num 这样写可以不用改 后面生产者消费者的代码
    18.         idx = rule.findall(urls)[0]
    19.         # payload参数 只需要更改 idx 就行
    20.         payload = {
    21.                 "CategoryType": "SiteHome",
    22.                 "ParentCategoryId": 0,
    23.                 "CategoryId": 808,
    24.                 "PageIndex": idx,
    25.                 "TotalPostCount": 4000,
    26.                 "ItemListActionName": "AggSitePostList"
    27.         }
    28.         r = requests.post(url, data=json.dumps(payload), headers=headers)
    29.         return r.text
    30. def parse(html):
    31.         # post-item-title
    32.         soup = BeautifulSoup(html, "html.parser")
    33.         links = soup.find_all("a", class_="post-item-title")
    34.         return [(link["href"], link.get_text()) for link in links]
    35. if __name__ == '__main__':
    36.         for res in parse(craw(urls[2])):
    37.                 print(res)
    复制代码

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

x
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

麻花痒

金牌会员
这个人很懒什么都没写!

标签云

快速回复 返回顶部 返回列表