当前位置:   article > 正文

用BeautifulSoup爬取微博热搜,并写入csv文件_美丽汤爬取微博热搜榜内容,并存储为csv文件

美丽汤爬取微博热搜榜内容,并存储为csv文件

 需要提前安装requests和bs4库:

  1. #爬虫两种获取HTML文本信息的方法,来自bs4的BeautifulSoup和lxml的etree
  2. #本文介绍第一种写法来自bs4的BautifulSoup
  3. import requests
  4. from bs4 import BeautifulSoup
  5. #爬取网站地址
  6. url="https://tophub.today/n/KqndgxeLl9"
  7. #伪装浏览器浏览信息,获取user-Agent(在chrome浏览器输入 chrome://version )
  8. header={'user-Agent':"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4844.82 Safari/537.36"}
  9. #抓取网站信息
  10. response = requests.get(url,headers=header)
  11. res=response.text#转化为spring类型
  12. soup=BeautifulSoup(res,features="lxml")
  13. heat=soup.select('tr td')
  14. for h in heat:
  15. print(h.get_text())
  16. s='num,title,heat\n'
  17. for i in range(len(heat)):
  18. if (i+1)%4!=0:
  19. s+=heat[i].get_text()+","
  20. else:
  21. s+="\n"
  22. with open('1.csv','w',newline='',encoding='utf8') as fw:
  23. fw.write(s)

得出的结果:

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/article/detail/57154?site
推荐阅读
相关标签
  

闽ICP备14008679号