关键词搜索

源码搜索 ×
×

Python笔记-获取某百科页面所有URL(提取某百科所有URL)

发布2021-08-10浏览918次

详情内容

程序运行截图如下:

这里分析下页面:

 

 凡是百度百科的都是在此url上

https://baike.baidu.com/item/

xxxxx,所以可以直接提取。

这里我们用个队列,将这个页面的所有有关的url入队,然后出队列,进行访问:

还有个要注意的,要伪造成浏览器,不然会回数据

  1. import requests
  2. import queue
  3. import time
  4. from bs4 import BeautifulSoup
  5. header = {
  6. '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',
  7. 'Accept-Language' : 'zh-CN,zh;q=0.9',
  8. 'Cache-Control' : 'no-cache',
  9. 'Connection' : 'keep-alive',
  10. 'Cookie' : 'xxxxxxx',
  11. 'Host' : 'baike.baidu.com',
  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://baike.baidu.com/item/"
  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('%E7%BB%9F%E8%AE%A1%E5%AD%A6/1175')
  24. for i in range(100):
  25. url = urlQueue.get()
  26. content = getRequest(baseUrl + url)
  27. contentSoup = BeautifulSoup(content, "html.parser")
  28. urlAllList = contentSoup.select("a")
  29. for urlTmp in urlAllList:
  30. if urlTmp.attrs.__contains__('href'):
  31. urlString = urlTmp['href']
  32. if '/item' in urlString:
  33. testUrl = urlString.split('/item/')[1]
  34. urlQueue.put(testUrl)
  35. pass
  36. pass
  37. pass
  38. print('over')
  39. pass

相关技术文章

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

提示信息

×

选择支付方式

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