关键词搜索

源码搜索 ×
×

Python笔记-获取某贴吧页面所有的贴吧id

发布2021-08-10浏览658次

详情内容

这里要注意,获取贴吧ID有防爬虫,他会把数据用<!-- -->这个注释掉。

运行截图如下:

注意要伪造成浏览器,不然获取不到数据

代码如下:

  1. import requests
  2. import queue
  3. import time
  4. from bs4 import BeautifulSoup
  5. header = {
  6. 'Host' : 'tieba.baidu.com',
  7. 'Accept' : 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',
  8. 'Accept-Language' : 'zh-CN,zh;q=0.9',
  9. 'Cache-Control' : 'no-cache',
  10. 'Connection' : 'keep-alive',
  11. 'Cookie' : 'xxxxxxxxxxxxxxxx',
  12. 'Pragma' : 'no-cache',
  13. 'User-Agent' : 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.114 Safari/537.36',
  14. 'sec-ch-ua' : '" Not;A Brand";v="99", "Google Chrome";v="91", "Chromium";v="91"'
  15. }
  16. baseUrl = "https://tieba.baidu.com/f?kw=%E5%B8%9D&ie=utf-8"
  17. urlQueue = queue.Queue(10000)
  18. def getRequest(url):
  19. response = requests.get(url, headers = header)
  20. return response.text
  21. pass
  22. if __name__ == '__main__':
  23. urlQueue.put(baseUrl)
  24. for i in range(100):
  25. url = urlQueue.get()
  26. content = getRequest(baseUrl + url)
  27. content = content.replace('-->', '').replace('<!--', '')
  28. contentSoup = BeautifulSoup(content, "html.parser")
  29. urlAllList = contentSoup.select("a")
  30. for urlTmp in urlAllList:
  31. if urlTmp.attrs.__contains__('href'):
  32. urlString = urlTmp['href']
  33. if '/p/' in urlString:
  34. testUrl = urlString.split('/p/')[1]
  35. urlQueue.put(testUrl)
  36. pass
  37. pass
  38. pass
  39. print('over')
  40. pass

 

相关技术文章

点击QQ咨询
开通会员
返回顶部
×
微信扫码支付
微信扫码支付
确定支付下载
请使用微信描二维码支付
×

提示信息

×

选择支付方式

  • 微信支付
  • 支付宝付款
确定支付下载